Angular 2 - Add a validator after initializing control

I am wondering how I can add a validator to an already created formControl (which was created with its own Validators). But imagine that after some delay, I want to add another one (or I have my own control that contains several validators), and I want to create an external reactive form and add internal validators to the external ones.

Is it possible? I did not find any information (only about reconfiguring 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 another validator inside my custom controls. How can i do this?

custom_coontrol.ts

this.outerFormControl.push(Validators.maxLength(10));
+4
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

+6

Source: https://habr.com/ru/post/1659738/


All Articles