Angular 2 - Add validator after control initializa

2019-06-19 16:36发布

问题:

I am wondering how I can add an validator to already created formControl (that was created with it own Validators). But, let's imagine that after some delay I want to add another one (or I have a custom control that contains a few validators itself) and I want to create outer Reactive form and add inner validators to outer.

Is it possible? I didn't found any information (only about re-setting all validators) Thanks for any help!

  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>

and after that I want to add other validator inside my custom controls. How I can do that?

custom_coontrol.ts

this.outerFormControl.push(Validators.maxLength(10));

回答1:

@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));
  }
}

Plunker