Last active
February 28, 2021 16:24
-
-
Save ssougnez/ec9e13321cbc12cc5be0c9b470f41632 to your computer and use it in GitHub Desktop.
This file contains 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 { ChangeDetectionStrategy, Component, Input, Output, EventEmitter, ChangeDetectorRef, forwardRef } from '@angular/core'; | |
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; | |
@Component({ | |
selector: 'app-on-off', | |
templateUrl: './on-off.component.html', | |
styleUrls: ['./on-off.component.scss'], | |
changeDetection: ChangeDetectionStrategy.OnPush, | |
host: { | |
'role': 'checkbox', | |
'[attr.aria-checked]': '!!value ? "true" : "false"', | |
'[attr.aria-disabled]': '!!disabled ? "true" : "false"', | |
'[class.disabled]': 'disabled', | |
'[attr.tabIndex]': 'disabled === true ? null : "0"', | |
'(keydown.arrowleft)': 'switch(true)', | |
'(keydown.arrowright)': 'switch(false)', | |
'(blur)': 'onTouched && onTouched()' | |
}, | |
providers: [ | |
{ | |
provide: NG_VALUE_ACCESSOR, | |
multi: true, | |
useExisting: OnOffComponent | |
} | |
] | |
}) | |
export class OnOffComponent implements ControlValueAccessor { | |
@Input() | |
public get value(): boolean { return this._value; } | |
public set value(obj: boolean) { | |
this.switch(obj); | |
} | |
@Input() | |
public disabled: boolean = false; | |
@Output() | |
public change: EventEmitter<boolean> = new EventEmitter<boolean>(); | |
public onChange: (value: boolean) => void; | |
public onTouched: () => void; | |
private _value: boolean = false; | |
constructor(private _cdr: ChangeDetectorRef){} | |
public switch(value: boolean) { | |
if (value !== this.value && this.disabled === false) { | |
this._value = value; | |
this.change.emit(this.value); | |
if (this.onChange) { | |
this.onChange(this.value); | |
} | |
this._cdr.markForCheck(); | |
} | |
} | |
public setDisabledState?(isDisabled: boolean): void { | |
this.disabled = isDisabled; | |
} | |
public writeValue(obj: any): void { | |
this.value = !!obj; | |
} | |
public registerOnChange(fn: any): void { | |
this.onChange = fn; | |
} | |
public registerOnTouched(fn: any): void { | |
this.onTouched = fn; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment