Skip to content

Instantly share code, notes, and snippets.

@armanozak
Last active June 4, 2019 08:05
Show Gist options
  • Save armanozak/84c89d9e5e878f916e8f542ce7b84161 to your computer and use it in GitHub Desktop.
Save armanozak/84c89d9e5e878f916e8f542ce7b84161 to your computer and use it in GitHub Desktop.
An Abstract Component with Accessible Value and More #blog
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