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 the 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.
Top comments (0)