Requiring a checkbox to be checked
You could just use a ValidatorPattern and check for the right (boolean) value:
<input type="checkbox" [formControl]="myForm.controls['isTosRead']">
and here is the binding:
this.myForm = builder.group({
isTosRead: [false, Validators.pattern('true')]
});
<h1>LOGIN</h1>
<form [formGroup]="signUpForm">
<input type="checkbox" formControlName="cb">
<button type="submit" [disabled]="!loginForm.valid" (click)="doLogin()">Log in</button>
</form>
export class Login {
public signUpForm: FormGroup;
constructor(fb: FormBuilder) {
this.signUpForm = fb.group({
cb: [false, Validators.requiredTrue]
});
}
doLogin() {
}
}
Since Angular 2.3.1 you can use Validators#requiredTrue
:
Component:
this.formGroup = this.formBuilder.group({
cb: [false, Validators.requiredTrue]
});
Template:
<form [formGroup]="formGroup">
<label><input type="checkbox" formControlName="cb"> Accept it</label>
<div style="color: red; padding-top: 0.2rem" *ngIf="formGroup.hasError('required', 'cb')">
Required
</div>
<hr>
<div>
<button type="submit" [disabled]="formGroup.invalid">Submit</button>
</div>
</form>
STACKBLITZ DEMO