简体   繁体   English

Angular2模型驱动的形式与模板驱动的形式

[英]Angular2 Model driven forms versus Template driven forms

I am using Angular2. 我正在使用Angular2。 I want to do form validations. 我想进行表单验证。 Currently my template looks like this: 目前,我的模板如下所示:

<form #f="ngForm" novalidate (ngSubmit)="save()">
        <input type="checkbox" name="showHydroSystemSelection" [(ngModel)]="cosResponse.showHydroSystemSelection.value" (ngModelChange)="onChange(cosResponse.showHydroSystemSelection.shouldRefresh)"/>
        <label>System Selection</label>
        <select name="systemSelection" id="systemSelection" [(ngModel)]="cosResponse.systemSelection.selected" (ngModelChange)="onChange(cosResponse.systemSelection.shouldRefresh)">
            <option *ngFor="let option of cosResponse.systemSelection.value" value="{{option.id}}" >
            {{option.name}}
            </option>
        </select>

</form>

In many blogs on how to do angular2 validations, they say to use a formGroup on the form. 在许多有关如何进行angular2验证的博客中,他们说要在表单上使用formGroup。 But if I do that, then angular complains with the error: " ngModel cannot be used to register form controls with a parent formGroup directive. Try using formGroup's partner directive "formControlName" instead" 但是,如果我这样做,则angular会报错:“ ngModel无法用于通过父formGroup指令注册表单控件。请尝试使用formGroup的伙伴指令” formControlName“代替”

The syntax for using ngModel is very good and dynamic for our app which totally depends on metadata to render different elements. 对于我们的应用程序,使用ngModel的语法非常好且动态,它完全依赖于元数据来呈现不同的元素。 The formGroup as a model is too explicit and static for our needs. 作为一个模型,formGroup对于我们的需求而言过于明确和静态。 I don't understand what are these two ways of using the model, and how to use formGroup effectively and as easily as ngModel 我不明白这两种使用模型的方式是什么,以及如何像ngModel一样有效且容易地使用formGroup

You are correct @vanval! 您是正确的@vanval!

I think that it´sa discussion about code , strategy and user experience . 我认为这是关于代码策略用户体验的讨论。

In summary we change for template-driven approach which is more easy to work with it, to reactive (in model-driven approach) for giving us more control , that results in a better testable form by leveraging a decoupling between the HTML (design/CSS team can work here) and component's business rules (angular/js specialist members) and to improve the user experience with features like reactive transformations, correlated validations and handle complex scenarios as runtime validation rules and dynamic fields duplication. 总而言之,我们将模板驱动方法(它更易于使用)更改为反应性 (在模型驱动方法中)以提供更多控制权 ,通过利用HTML(设计/ CSS团队可以在这里工作)和组件的业务规则(Angular / js专家成员),并利用诸如响应式转换,相关验证之类的功能来改善用户体验 ,并处理复杂的场景,如运行时验证规则和动态字段重复。

This article is a good reference about it: Angular 2 Forms - Template Driven and Model Driven Approaches 本文对此有很好的参考: Angular 2表单-模板驱动和模型驱动方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM