What is the difference between the two:
<form #form="ngForm">
And
<form [ngFormModel]="form">
When do you use one over the other?
The first strategy is a 'template-driven' form: Angular will add an implicit directive to the form and you add validators mostly declaratively in the template, and so the name 'template-driven'. For example this is how to add a validator saying that the field is required:
<form #form="ngForm">
<input name="firstName" required [(ngModel)]="formModel">
</form>
Here we have used the required attribute, and Angular via an implicit directive has configured the required Validator. This type of form is very well-suited to be used with ng-model, and ideal for migrating Angular 1 forms to Angular 2.
The second strategy is a 'model-driven' form. Here we don't declare validators on the template, instead we declare control names:
<form [formGroup]="form">
<input name="firstName" formControlName="firstName">
</form>
Then, all the validation logic is declared via code and not in the template. Also we can subscribe to the form as an Observable and use functional reactive programming techniques. For example:
@Component({
selector: "some-component",
templateUrl: 'model-driven-form.html'
})
export class ModelDrivenForm {
form: FormGroup;
firstName = new FormControl ("", Validators.required);
constructor(fb: FormBuilder) {
this.form = fb.group({
"firstName":["", Validators.required]
});
this.form.valueChanges
.subscribe((formValue) => {
console.log(formValue);
});
}
}
This also works with NgModel
but as we see it would not be needed, because we already can obtain the the value of the form via the form control.
So choosing between both depends a lot on the use case:
formGroup
option 2formGroup
, although definitively give it a try, its very powerfulP.S. See more on new forms in Angular2 here