如何将2种方式的数据绑定与模型驱动的表单结合起来? [英] How to combine 2 way databinding with model driven forms?

查看:76
本文介绍了如何将2种方式的数据绑定与模型驱动的表单结合起来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在角度2中,构建形式的一种可能性是模型驱动方式.据我了解,与ngModel的模板驱动方式相反,控件会松开其2种方式的数据绑定.

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.

将2种方式的数据绑定与模型驱动的表单相结合的最佳方法是什么? 我尝试将模型绑定与[值]结合使用:

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.

我正在使用角度2 beta.15.

I'm using angular 2 beta.15.

推荐答案

实际上,您可以像这样混合ngControlngModel:

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>

在这种情况下,您在hero.value.name上进行双向绑定. ngModel允许在输入字段上附加属性并使它们同步(双向绑定).控件允许应用验证,如果字段有效,被触摸等则得到通知,并通知更新(valueChanges).

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).

查看此插件: https://plnkr.co/edit/XnfGDE7vTTogH8yxtxjo?p=preview .

也就是说,您可以混合使用内联(ngControl)和程序化表单定义(ngFormModel).

That said you can mix inline (ngControl) and programmatic form definition (ngFormModel).

有关更多详细信息,请参见本文:

See this article for more details:

这篇关于如何将2种方式的数据绑定与模型驱动的表单结合起来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆