Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscribe to input errors in Angular reactive form

I have Angular reactive form, where every input is a separated component which receive parent form as @Input(). Inside this component I want to subscribe to his errors, and change variable value, if there is some errors. Errors for every control can came not only from value change, so I can't check errors on blur or on value change. What is the correct way to do this?

form.html

<form [formGroup]="formName">
   <app-input-group [parentForm]="formName" [name]="controlName"></app-input-group>
</form>

input-group.ts

export class InputGroupComponent {
  @Input parentForm: FormGroup
  @Input name: string

  public status: string

  // Need to call this function when control in form have errors
  public getStatus() {
     if (this.parentForm.get(this.name).errors) {
        this.status = 'suspended'
     } else {
        this.status = 'boosted'
     }
  }
}
like image 821
Vladimir Humeniuk Avatar asked Jul 23 '26 06:07

Vladimir Humeniuk


1 Answers

you can subscribe to statusChanges on any form control/group/array:

this.parentForm.get(this.name).statusChanges.subscribe(v => this.getStatus());

it emits on all validation status changes of the form...

alternatively, you could define your status variable differently:

get status() {
    return (this.parentForm.get(this.name).errors) ? 'suspended' : 'boosted';
}

but this may not be appropriate for your use case.

like image 179
bryan60 Avatar answered Jul 24 '26 19:07

bryan60