Created
September 18, 2017 20:07
-
-
Save alexxxnf/7183b34d447e7114fafb9db7952d257d to your computer and use it in GitHub Desktop.
Angular checkbox control accessor returning its value instead of true/false
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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