Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alexxxnf/7183b34d447e7114fafb9db7952d257d to your computer and use it in GitHub Desktop.
Save alexxxnf/7183b34d447e7114fafb9db7952d257d to your computer and use it in GitHub Desktop.
Angular checkbox control accessor returning its value instead of true/false
import {Directive, ElementRef, Renderer2, forwardRef, Input} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
export const CHECKBOX_VALUE_OVERRIDE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => AdvancedCheckboxControlValueAccessor),
multi: true,
};
/**
* The accessor for writing a value and listening to changes on a checkbox input element.
* Writes `value` if checked and `offvalue` otherwise.
*
* ### Example
* ```
* <input type="checkbox" name="rememberLogin" ngModel value="On" offvalue="Off">
* ```
*
* ### Installation
* ```
* import {AdvancedCheckboxControlValueAccessor} from 'advanced-checkbox-control-value-accessor.directive';
* @NgModule({
* declarations: [
* AdvancedCheckboxControlValueAccessor
* ]
* })
* export class AppModule {
* }
* ```
*/
@Directive({
selector: 'input[type=checkbox][formControlName],input[type=checkbox][formControl],input[type=checkbox][ngModel]',
host: {'(change)': 'onChange()', '(blur)': 'onTouched()'},
providers: [CHECKBOX_VALUE_OVERRIDE_ACCESSOR]
})
export class AdvancedCheckboxControlValueAccessor implements ControlValueAccessor {
_state: boolean;
_fn: Function;
onChange = (_: any) => {};
onTouched = () => {};
@Input() value: any;
@Input() offvalue: any = null;
constructor(private _renderer: Renderer2, private _elementRef: ElementRef) {}
writeValue(value: any): void {
this._state = value === this.value;
this._renderer.setProperty(this._elementRef.nativeElement, 'checked', this._state);
}
registerOnChange(fn: (_: any) => {}): void {
this._fn = fn;
this.onChange = () => {
fn(this._elementRef.nativeElement.checked ? this.value : this.offvalue);
};
}
registerOnTouched(fn: () => {}): void { this.onTouched = fn; }
setDisabledState(isDisabled: boolean): void {
this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment