ar099968
ar099968

Reputation: 7537

Angular reactive forms: how show validation errors in a dialog?

I have a Angular reactive forms and i want show validation errors in a material dialog.

There is a way for subscribe formControl.errors and on error do something?

EG.:

this.formControl.errors.subscribe(errors => {
    this.dialog.open(DialogAlertComponent, {data: errors});
});

Upvotes: 1

Views: 1823

Answers (1)

Meyyappan Subramaniyan
Meyyappan Subramaniyan

Reputation: 363

To show errors when there is a statusChange or valueChange in your form, you can make use of the below 2 observables on your formGroup object.

  • valueChanges: Observable --> emits an event every time the value of the control changes
  • statusChanges: Observable ---> emits an event every time the validation status of the control recalculates.
form: FormGroup;
constructor(private formBuilder: FormBuilder) {}

this.form = this.formBuilder.group({
  username: ['', [ Validators.required ]],
  password: ['', [ Validators.required ]]
});

To monitor a single formcontrol,

this.form.get('username').valueChanges.subscribe(
  result => {
    // call your DialogAlertComponent to show errors if any
  }
); 

To monitor the entire form,

this.form.valueChanges.subscribe(
  result => {
    // call your DialogAlertComponent to show errors if any
  }
);

Here statusChanges Observable can also be used.

Upvotes: 2

Related Questions