Template-driven forms menggunakan directive di template untuk mengelola form.
Contoh Form
@Component({
imports: [FormsModule],
template: `
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
<input name="email" ngModel required email />
<input name="password" ngModel required minlength="6" type="password" />
@if (myForm.controls["email"]?.errors?.["required"]) {
<p>Email wajib diisi</p>
}
<button [disabled]="myForm.invalid">Submit</button>
</form>
`,
})
export class FormComponent {
onSubmit(form: NgForm) {
console.log(form.value)
}
}
Template-driven forms cocok untuk form sederhana. Gunakan Reactive Forms untuk form kompleks.