为动态表单创建自定义验证器 angular 2

Create custom validators for dynamic forms angular 2

我只是红了 angular 2 食谱,介绍了如何创建动态表单,但我想知道如何将自定义验证器添加到特定字段。

questions.forEach(question => {
  group[question.key] = question.required ? new FormControl(question.value || '', Validators.required)
                                          : new FormControl(question.value || '');
});

这里他们形成了一个 from group 来保存表单输入,所以如果我想对特定问题应用特定验证怎么办 例如:如果我有确认密码匹配的输入。 我知道有 validateequal 属性可以完成这个任务,我如何应用这个 validateequal 甚至创建我自己的自定义验证

注意它是动态表单,这意味着可以保存任何输入,例如我打算使用相同的表单来生成登录表单,这意味着它只有密码输入,我需要检查是否有输入将保存密码,如果有输入将保存密码确认,如果是,那么我需要在提交之前检查它们是否匹配

好的,我想我有。

您将使用自定义指令来完成工作。

这是一个关于自定义指令的非常基本的教程https://angular.io/docs/ts/latest/guide/attribute-directives.html

如果您创建应用程序模板,则可以轻松修改它以适合您的参数。

在我的例子中,我按以下方式使用了该示例。

你的 NgModule || app.module.ts

import { customDirective } from '../directive/path';

你的customDirective.ts || js

import {Directive, HostListener, Input, ElementRef} from '@angular/core';
@Directive({
   selector: '[fooSelector]'
})

export class CustomDirective {
  constructor(private el: ElementRef, private renderer: Renderer) {}
  @Input('fooSelector') testing: Object;

  //this controls event type with change being the event
  @HostListener('change') onChange(){
    this.logicFunct(this.htmlAttr); //will define htmlAttr in template
  }

  //this is the validator logic
  private logicFunct($obj: Object){
    // submit logic here - for ex:
    if($obj != 'test) {
      this.varBar = true; //check template ngIf
    }
  }
}

您的模板

<input
  type="text"
  #htmlAttr
  [fooSelector]="this.htmlAttr._value"
  *ngIf="!this.varBar">
</input>

我几乎肯定还有其他更好的方法可以做到这一点,如果有人有,请告诉我们!

希望这对任何偶然发现它的人有所帮助。