Customizing the default value for a checkbox may be necessary in some cases. You have the option to create your own checkbox logic that defines values for both the checked and unchecked states.
To learn more, refer to the Angular documentation on ControlValueAccessor.
An example implementation can be found on StackBlitz.
app.component.ts
import { Component, OnInit } from "@angular/core";
import { FormControl, Validators } from "@angular/forms";
@Component({
selector: "my-app",
template: `
<app-custom-checkbox
[checkedValue]="checked"
[unCheckedValue]="unChecked"
[formControl]="formControl"
>
{{ checked }}/{{ unChecked }}
</app-custom-checkbox>
`,
styles: [""]
})
export class AppComponent implements OnInit {
readonly checked = "Salary";
readonly unChecked = "Hourly";
formControl = new FormControl(this.unChecked, Validators.required);
ngOnInit() {
this.formControl.valueChanges.subscribe(console.log);
}
}
custom-checkbox.component.ts
import { Component, forwardRef, Input, OnInit } from "@angular/core";
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";
export const CHECKBOX_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomCheckboxComponent),
multi: true
};
@Component({
selector: "app-custom-checkbox",
template: `
<label>
<input
type="checkbox"
[checked]="checkedValue === value"
(change)="onChanged($event)"
[disabled]="disabled"
/>
<ng-content></ng-content>
</label>
`,
styles: [""],
providers: [CHECKBOX_VALUE_ACCESSOR]
})
export class CustomCheckboxComponent implements OnInit, ControlValueAccessor {
@Input()
checkedValue: string = "true";
@Input()
unCheckedValue: string = "false";
value: string = this.unCheckedValue;
onChange = (_: any) => {};
onTouched = () => {};
disabled = false;
constructor() {}
ngOnInit() {}
onChanged(event) {
const isChecked = event && event.target && event.target.checked;
this.onChange(isChecked ? this.checkedValue : this.unCheckedValue);
}
writeValue(value: any): void {
this.value = value;
}
registerOnChange(fn: (_: any) => {}): void {
this.onChange = fn;
}
registerOnTouched(fn: () => {}): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
}