import { Directive , OnInit , Input , HostBinding , HostListener , Self , Renderer , ElementRef } from '@angular/core' ; import { ControlValueAccessor , NgModel } from '@angular/forms' ; @ Directive ( { selector : '[btnCheckbox][ngModel]' } ) export class ButtonCheckbox implements ControlValueAccessor , OnInit { @ Input ( ) private btnCheckboxTrue : any ; @ Input ( ) private btnCheckboxFalse : any ; @ HostBinding ( 'class.active' ) private state : boolean = false ; @ HostListener ( 'click' , [ '$event.target' ] ) private onClick ( target ) { var target = target . classList ; this . toggle ( ! this . state ) ; this . cd . viewToModelUpdate ( this . value ) ; } private value : any ; constructor ( @ Self ( ) public cd ) { cd . valueAccessor = this ; } public ngOnInit ( ) { this . toggle ( this . trueValue === this . value ) ; } private get trueValue ( ) { return typeof this . btnCheckboxTrue !== 'undefined' ? this . btnCheckboxTrue : true ; } private get falseValue ( ) { return typeof this . btnCheckboxFalse !== 'undefined' ? this . btnCheckboxFalse : false ; } private toggle ( state ) { this . state = state ; this . value = this . state ? this . trueValue : this . falseValue ; } public writeValue ( value ) { this . state = this . trueValue === value ; this . value = value ; } protected onChange = ( _ ) => { } ; protected onTouched = ( ) => { } ; public registerOnChange ( fn ) { this . onChange = fn ; } public registerOnTouched ( fn ) { this . onTouched = fn ; } }