问题
In angular 2 one possibility of building forms is the model driven way. As far as I understand, the controls loose their 2 way databinding, in opposite to the template driven way with ngModel.
What is the best way of combining 2 way data binding with model driven forms? I tryed to use model binding with [value] :
<form [ngFormModel]="hero" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" [value]="hero.value.name"
class="form-control" ngControl="name">
That seems to work: If the model is changed programmatically, the control is also updated.
But I'm not sure if this is the correct way. I noticed, if I try to update the validations by
this.hero.updateValueAndValidity();
in a timeout function, the controls value and the model are resetted to the original value.
I'm using angular 2 beta.15.
回答1:
In fact you can mix ngControl
and ngModel
like this:
<form ngForm="hero" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" [(ngModel)]="hero.value.name"
class="form-control" ngControl="name">
</div>
</form>
In this case, you have two-way binding on the hero.value.name
. ngModel
allows to attach properties on input fields and make them synchronized (two-way binding). Controls allow to apply validation, get informed if fields are valid, touched, ... and to be notified of updates (valueChanges
).
See this plunkr: https://plnkr.co/edit/XnfGDE7vTTogH8yxtxjo?p=preview.
That said you can mix inline (ngControl
) and programmatic form definition (ngFormModel
).
See this article for more details:
- http://restlet.com/blog/2016/02/11/implementing-angular2-forms-beyond-basics-part-1/
来源:https://stackoverflow.com/questions/36843938/how-to-combine-2-way-databinding-with-model-driven-forms