I want a button to be disabled until a checkbox has been checked using a FormBuilder for Angular. I don't want to explicitly check the value of the checkbox and would prefer to use a validator so that I can simply check form.valid
.
In both validation cases below the checkbox is
interface ValidationResult { [key:string]:boolean; } export class CheckboxValidator { static checked(control:Control) { return { "checked": control.value }; } } @Component({ selector: 'my-form', directives: [FORM_DIRECTIVES], template: ` <form [ngFormModel]="form" (ngSubmit)="onSubmit(form.value)"> <input type="checkbox" id="cb" ngControl="cb"> <button type="submit" [disabled]="!form.valid"> </form>` }) export class SomeForm { regForm: ControlGroup; constructor(fb: FormBuilder) { this.form = fb.group({ cb: [ CheckboxValidator.checked ] //cb: [ false, Validators.required ] <-- I have also tried this }); } onSubmit(value: any) { console.log('Submitted: ', this.form); } }
Add checked = "checked" to the input you want selected. For XHTML the recommended way is as described. Check HTML manual and W3C to confirm. The markup posted isn't XHTML, so it's logical to use just the simple keyword attribute checked .
The required property sets or returns whether a checkbox must be checked before submitting a form. This property reflects the HTML required attribute.
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
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')] });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With