How to check the status of an Angular Reactive Form’s Control

Sometimes, you may have a requirement to do something when the status of an Angular form control changes.  For example, you have a Login Form, and when the status of the Email control changes from valid to invalid and vice versa, you need to perform some actions. In this post, let us see how we can achieve that.

We have a login form,

fb = inject(FormBuilder);
  loginForm: FormGroup;
  
  constructor() {

    this.loginForm = this.fb.group({
      email: [null, [Validators.required]],
      password: [null, [Validators.required]],
    })
  }

On the template, map the loginForm to the HTML Form element and FormControls to the input elements.

<form (ngSubmit)="login()" [formGroup]="loginForm" novalidate>
<input type="text" formControlName="email" placeholder="Enter email" />
<br/>
<input type="password" formControlName="password" placeholder="Enter Password"/>
<br/>
<br/>
<button>Login</button>
</form>

Now whenever the status of the email field changes, you need to take some action.  For that, Angular AbstractControlDirective provides a getter of an observable type called statusChanges().

You can subscribe to the statusChanges() observable to work with control’s status change.

checkControlStatus(){

    const email = this.loginForm.get('email'); 
    email?.statusChanges.subscribe((status:any)=>{
       console.log(status);
    })
  }

And further, call the above function In the ngOnInit() life cycle hook.

ngOnInit(): void {
    this.checkControlStatus();
  }

You can check the status for valid or invalid and apply conditional css or log to the API etc. I hope you find this post helpful. Thanks for reading.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com