Angular 2 - 在控制初始化后添加验证器

Vel*_*dan 6 forms validation angular

我想知道如何为已经创建的formControl添加验证器(使用它自己的Validators创建).但是,让我们想象一下,经过一段时间后我想添加另一个(或者我有一个自定义控件,其中包含一些验证器),我想创建外部Reactive表单并将内部验证器添加到外部.

可能吗?我没有找到任何信息(仅关于重新设置所有验证器)感谢您的帮助!

  this.testForm = this.fb.group({
      testField: [{value: '', disabled: false}, [<any>Validators.required]]
    })

<form [formGroup]="testForm" novalidate>
  <custom_input>
    formControlName="testField"
    [outerFormControl]="testForm.controls.testField"
    </custom_input>


</form>
Run Code Online (Sandbox Code Playgroud)

之后我想在我的自定义控件中添加其他验证器.我怎么能这样做?

custom_coontrol.ts

this.outerFormControl.push(Validators.maxLength(10));
Run Code Online (Sandbox Code Playgroud)

Baz*_*nga 9

@Component({
  selector: 'my-app',
  template: `
   <form [formGroup]="testForm" novalidate>
    <input type="text" formControlName="age">
   </form>
   <button (click)="addValidation()">Add validation</button>

   {{ testForm.valid | json }}
  `,
})
export class App {

  constructor(private fb: FormBuilder) {
     this.testForm = this.fb.group({
      age: [null, Validators.required]
    })
  }

  addValidation() {
    this.testForm.get('age').setValidators(Validators.maxLength(2));
  }
}
Run Code Online (Sandbox Code Playgroud)

Plunker

  • 凉.有用.谢谢帕特里克!但它怎么可能呢?我读到使用SetValidators将覆盖以前的validatords.NG2 API:**设置在此控件上处于活动状态的同步验证器.调用此方法将覆盖任何现有的同步验证器.** (2认同)
  • 好的,我检查了源代码,如果传递的验证器将在数组中,此方法将为存在的验证器添加新的验证器.在其他情况下,它将覆盖以前的验证器.这是源:**函数coerceToValidator(验证器:ValidatorFn | ValidatorFn []):ValidatorFn {return Array.isArray(validator)?composeValidators(validator):验证器; }** (2认同)