7

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'
     }
  }
}

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.