首页 > 解决方案 > 如何为 FormGroup 创建自定义验证器

问题描述

我有一个带有 6 个字段的 formGroup 对象。6 个字段中有 5 个是强制性的,这意味着它们中的任何一个都必须具有值才能成为有效的表单。5 个字段中的哪一个具有值并不重要,只要其中一个具有值即可。如何为表单添加自定义验证器?

标签: angularangular-formsangular-formbuilder

解决方案


假设您使用模板驱动表单的 2 方式绑定。

@Component({
  selector: 'my-component',
  template: `
      ...
      <input name="input1" [(ngModel)]="input1" [required]="!checkIfValueExists()"/>          
      <input name="input2" [(ngModel)]="input2" [required]="!checkIfValueExists()"/>     
      <input name="input3" [(ngModel)]="input3" [required]="!checkIfValueExists()"/>     

  `
})
export class MyComponent {
    input1: string;
    input2: string;
    input3: string;

    constructor() {}

    checkIfValueExists(): boolean {
        return input1 || input2 || input3;
    }
}

推荐阅读