Issue
I am using Angular Forms to make a simple form with email, password and a checkbox for Terms&Conditions in my Ionic app. My HTML:
<form [formGroup]="registerForm" (ngSubmit)="register()" class="center">
<ion-item class="input-field">
<ion-input type="email" formControlName="email" placeholder="Email"></ion-input>
</ion-item>
<ion-item class="input-field">
<ion-input type="password" formControlName="password" placeholder="Password" ></ion-input>
</ion-item>
<ion-item no-lines>
<ion-checkbox formControllName="termsAndConditions"></ion-checkbox>
<ion-label>Terms and Conditions</ion-label>
</ion-item>
<button ion-button full type="submit" [disabled]="!registerForm.valid">Register</button>
</form>
And a simple Angular component:
export class RegisterComponent {
registerForm: FormGroup;
email = new FormControl('', [Validators.required, Validators.email]);
password = new FormControl('', [Validators.required]);
termsAndConditions = new FormControl('', [Validators.required]);
constructor(private formBuilder: FormBuilder) {
this.registerForm = this.formBuilder.group({
email: this.email,
password: this.password,
termsAndConditions: this.termsAndConditions
});
}
}
I have a problem with checkbox validation which doesn't work as I assumed it should. Right now I can submit the form without the checkbox. I simply need to make it required - the same as other form values which already worked, how can I do it?
Solution
I managed to solve to problem using custom validator on the checkbox:
export class RegisterComponent {
registerForm: FormGroup;
email = new FormControl('', [Validators.required]);
password = new FormControl('', [Validators.required]);
termsAndConditions = new FormControl(undefined, [Validators.required]);
constructor(private formBuilder: FormBuilder) {
this.registerForm = this.formBuilder.group({
'email': this.email,
'password': this.password,
'termsAndConditions': this.termsAndConditions
}, {validator: this.checkCheckbox });
}
public checkCheckbox(c: AbstractControl){
if(c.get('termsAndConditions').value == false){
return false;
}else return true;
}
}
Now the checkbox works properly.
Answered By - UO Man
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.