ghostagent151
ghostagent151

Reputation: 1396

In an Angular 7 application, with reactive forms, how can i modify this method so that it will clear only invalid form controls within a form group?

I need to modify this method, so that when a user clicks on a button, all invalid form controls within the form group they are on, have their values reset or set to null.

The current method consists of this:

    disableControl(group: FormGroup){
      Object.keys(group.controls).forEach((key: string) => {
      const abstractControl = group.get(key);
      abstractControl.setValue(null)
      abstractControl.disable();
     })
    }

When the user clicks on a button, any invalid form controls should be set to null or reset.

Upvotes: 1

Views: 37

Answers (1)

AVJT82
AVJT82

Reputation: 73337

You can check if the form control is invalid:

disableControl(group: FormGroup) {
  Object.keys(group.controls).forEach((key: string) => {
    const abstractControl: AbstractControl = group.get(key);
    if (abstractControl.invalid) {
      abstractControl.reset();
      // .... or
      // abstractControl.setValue(null);
    }
 })
}

Upvotes: 1

Related Questions