Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Add validator after control initialization

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));
like image 490
Velidan Avatar asked Nov 03 '16 14:11

Velidan


People also ask

How will you add validators in form control?

We can add Validators dynamically using the SetValidators or SetAsyncValidators. This method is available to FormControl, FormGroup & FormArray. There are many use cases where it is required to add/remove validators dynamically to a FormControl or FormGroup.

Which method is used to add dynamic validation to the forms in angular?

Dynamically Add Validators We need to listen to optionB value changes and based on that we add or remove the validators we require. We also call the control's updateValueAndValidity() method, as we need to recalculate the value and validation status of the control.


1 Answers

@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

like image 90
Bazinga Avatar answered Nov 03 '22 00:11

Bazinga