如何将 2 路数据绑定与模型驱动形式相结合? [英] How to combine 2 way databinding with model driven forms?
问题描述
在 angular 2 中,构建表单的一种可能性是模型驱动的方式.据我了解,与 ngModel 的模板驱动方式相反,控件松散了 2 路数据绑定.
将 2 路数据绑定与模型驱动表单相结合的最佳方式是什么?我尝试将模型绑定与 [value] 结合使用:
这似乎有效:如果以编程方式更改模型,则控件也会更新.
但我不确定这是否是正确的方法.我注意到,如果我尝试通过
更新验证this.hero.updateValueAndValidity();
在超时函数中,控件值和模型被重置为原始值.
我使用的是 angular 2 beta.15.
事实上你可以像这样混合 ngControl
和 ngModel
:
</表单>
在这种情况下,您对 hero.value.name
进行了双向绑定.ngModel
允许在输入字段上附加属性并使它们同步(双向绑定).控件允许应用验证,在字段有效、触摸等情况下获得通知,并在更新时收到通知 (valueChanges
).
查看此 plunkr:https://plnkr.co/edit/XnfGDE7vTTogH8yxtxjo?p=preview.
也就是说,您可以混合使用内联 (ngControl
) 和程序化表单定义 (ngFormModel
).
查看这篇文章了解更多详情:
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.
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:
这篇关于如何将 2 路数据绑定与模型驱动形式相结合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!