Last active
June 4, 2019 08:05
-
-
Save armanozak/84c89d9e5e878f916e8f542ce7b84161 to your computer and use it in GitHub Desktop.
An Abstract Component with Accessible Value and More #blog
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 { ControlValueAccessor } from '@angular/forms'; | |
import { ChangeDetectorRef, Component, Injector, Input, Type } from '@angular/core'; | |
import { uuid } from '../utils/generators'; | |
@Component({ template: '' }) | |
export class AbstractNgModelComponent<T = any> implements ControlValueAccessor { | |
@Input() | |
cid: string = uuid(); | |
@Input() | |
disabled: boolean; | |
@Input() | |
set value(value: T) { | |
this._value = value; | |
this.notifyValueChange(); | |
} | |
get value(): T { | |
return this._value; | |
} | |
onChange: (value: T) => {}; | |
onTouched: () => {}; | |
protected _value: T; | |
protected cdRef: ChangeDetectorRef; | |
constructor(public injector: Injector) { | |
this.cdRef = injector.get<ChangeDetectorRef>(ChangeDetectorRef as Type<ChangeDetectorRef>); | |
} | |
notifyValueChange(): void { | |
if (this.onChange) { | |
this.onChange(this.value); | |
} | |
} | |
writeValue(value: T): void { | |
this._value = value; | |
setTimeout(() => this.cdRef.detectChanges(), 0); | |
} | |
registerOnChange(fn: any): void { | |
this.onChange = fn; | |
} | |
registerOnTouched(fn: any): void { | |
this.onTouched = fn; | |
} | |
setDisabledState(isDisabled: boolean): void { | |
this.disabled = isDisabled; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment