简体   繁体   English

Angular 2 中的模板驱动表单

[英]Template Driven Forms in Angular 2

Looking at the advantages and disadvantages of Template Driven vs. Model Driven Forms in Angular 2 (beta.0), I'm wondering how a custom validation can be attached to a simple text input field using Template Driven Forms.查看 Angular 2 (beta.0) 中模板驱动与模型驱动表单的优缺点,我想知道如何使用模板驱动表单将自定义验证附加到简单的文本输入字段。 There are no examples (beside required) available for this approach or I did not find them.这种方法没有可用的示例(除了必需的),或者我没有找到它们。

<form #f="ngForm">
  <label for="name">Name</label>
  <input type="text" ngControl="name" [(ngModel)]="obj.name" #name="ngForm">
  <button type="button" (click)="save()">Save</button>
</form>

As an example validation function:作为示例验证函数:

validate(control:Control):ValidationResult {
   if (control.value === 'Monkey') {
      return { invalidName: true }
   }
}

The above validation function works using in a Model Driven Form using FormBuilder.上述验证功能在使用 FormBuilder 的模型驱动表单中使用。 How could this be done using the Template Driven approach?如何使用模板驱动的方法来做到这一点?

An answer like "It's not possible and won't be in the future too."像“这是不可能的,将来也不会”这样的回答。 or "It's not best practise, go with the Model Driven approach."或“这不是最佳实践,请使用模型驱动方法。” together with an argument will be more than fine with me.再加上争论对我来说会更好。 (I already assume that there is no way but find no evidence in the web and I prefer the Model Driven approach more.) (我已经假设没有办法,但在网络上找不到任何证据,我更喜欢模型驱动方法。)

In template driven forms you need to create a directive for custom validator and append it to the input element like html attribute (the same way as you would append required attribute).在模板驱动的表单中,您需要为自定义验证器创建一个指令,并将其附加到输入元素,如 html 属性(与附加required属性的方式相同)。

You should read this article on how to create directives for custom validators: http://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html您应该阅读有关如何为自定义验证器创建指令的文章: http : //blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html

In Template driven froms you have to create directive for custom validator and use it to template elements.在模板驱动中,您必须为自定义验证器创建指令并将其用于模板元素。

here is my directive file,这是我的指令文件,

validator.directive.ts验证器指令.ts

import { Directive, forwardRef, Attribute } from '@angular/core';
import { Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms';

@Directive({
    selector: '[validateEqual][formControlName],[validateEqual][formControl],[validateEqual][ngModel]',
    providers: [
        { provide: NG_VALIDATORS, useExisting: forwardRef(() => EqualValidator), multi: true }
    ]
})
export class EqualValidator implements Validator {
    constructor( @Attribute('validateEqual') public validateEqual: string,
        @Attribute('reverse') public reverse: string) {

    }

    private get isReverse() {
        if (!this.reverse) return false;
        return this.reverse === 'true' ? true: false;
    }

    validate(c: AbstractControl): { [key: string]: any } {
        // self value
        let v = c.value;

        // control vlaue
        let e = c.root.get(this.validateEqual);

        // value not equal
        if (e && v !== e.value && !this.isReverse) {
          return {
            validateEqual: false
          }
        }

        // value equal and reverse
        if (e && v === e.value && this.isReverse) {
            delete e.errors['validateEqual'];
            if (!Object.keys(e.errors).length) e.setErrors(null);
        }

        // value not equal and reverse
        if (e && v !== e.value && this.isReverse) {
            e.setErrors({
                validateEqual: false
            })
        }

        return null;
    }
}

Template driven forms are quite easy to use.模板驱动的表单非常易于使用。 But as your application size increases it becomes complex to handle all the validations.但是随着应用程序大小的增加,处理所有验证变得复杂。 As the name suggests- Template driven all the code for form and its validation is done mainly on the html template only so your template code increases.顾名思义-模板驱动了表单的所有代码,其验证主要仅在 html 模板上完成,因此您的模板代码会增加。 While in case of React Forms/Model driven you need to configure your control fields in the typescript only.而在 React Forms/Model 驱动的情况下,您只需要在打字稿中配置您的控制字段。 So both are good and have there own advantages,so depending upon the requirement one should choose one from the other approach.所以两者都很好,都有自己的优势,所以根据要求,应该从另一种方法中选择一种。

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

相关问题 angular 模板驱动 forms 中的动态元素参考 - Dynamic element reference in angular template driven forms 模板驱动 Forms 需要允许空字符串 - Angular 7/8 - Template Driven Forms required allows empty string - Angular 7/8 如何在 Angular 中使用模板驱动的 forms 验证数字字段? - How to validate number fields with template driven forms in Angular? 即使regExp匹配,也认为Angular模板驱动的表单字段无效 - A field of Angular template driven forms considered invalid even though the regExp matches 如何使用全局变量启用或禁用 Angular 模板驱动表单中的按钮? - How to use a global variable to enable or disable a button in Angular template driven forms? 模板驱动形式将所有标记为已触摸 - Angular 7 - Template Driven Form Mark All as touched - Angular 7 Angular2模型驱动的表单中的单选按钮无法正常工作 - Radio buttons in Angular2 Model Driven forms not working as expected 如何在 Angular 中将此模板驱动形式更改为反应形式? - How to change this template driven form to Reactive form in Angular? 我使用 angular 模板驱动表单创建简单表单 - I create simple form using angular template driven form 如何在没有任何提交按钮的情况下提交模板驱动的角度表单? - How to submit a template driven angular form without any submit button?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM