FormGroup controls to enable & disable an Ion-button
Hi Everyone,
This post is to share my insight regarding the Formgroup which is a new thing that I have implemented & learned today( probably a cool thing that i learned today!).
Have you faced a scenario where you need to validate two input forms , whether they are same or not? & based on that enabling a continue button?
If you have faced & struck in between - May be this post can help you!
Suppose We have two input -fields as below:
As shown in the above image, the continue button will enable - This can be achieved with the FormGroup, FormControl from angular/forms.
Code to achieve the above requirement:
Create a Angular Ionic Project with the command :
ionic start <projectName>
In the html file:
<ion-header>
<ion-toolbar color="primary">
<ion-title>1.Formgroup Tutorial</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<form [formGroup]="pwdForm">
<div class="ion-padding">
<ion-input label="password" labelPlacement="stacked" placeholder="Please enter your new Password" fill="outline" formControlName="newPwd"></ion-input>
</div>
<div class="ion-padding">
<ion-input label="Confirm Password" labelPlacement="stacked" placeholder="Confirm your Password" fill="outline" formControlName="cnfNewPwd"></ion-input>
</div>
</form>
<ion-button expand="block" [disabled]="validForm">Continue</ion-button>
</ion-content>
In the .ts file:
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-formgroup-tut',
templateUrl: './formgroup-tut.page.html',
styleUrls: ['./formgroup-tut.page.scss'],
})
export class FormgroupTutPage implements OnInit {
constructor() { }
ngOnInit() {
}
// PIN Form
pwdForm : FormGroup = new FormGroup({
newPwd : new FormControl('', [Validators.required, Validators.minLength(6), Validators.maxLength(6)]),
cnfNewPwd : new FormControl('', [Validators.required, Validators.minLength(6), Validators.maxLength(6)])
});
get validForm() {
const valid=this.pwdForm.controls['newPwd'].value === this.pwdForm.controls['cnfNewPwd'].value;
const pin=this.pwdForm.controls['newPwd'].value;
if(pin && valid) {
return false;
}
return true;
}
}
The above validForm method will validate the value from the forms whether they are equal or not & enable the Continue Button.
Output:
The Button will enable if both forms are equal:
The Button will disable if both forms are not equal:
Hope this is useful!