Created
September 9, 2019 23:05
-
-
Save wesleyegberto/94b0b814debcbe283c115a76bb975104 to your computer and use it in GitHub Desktop.
Base class to create Angular components
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, NG_VALUE_ACCESSOR } from '@angular/forms'; | |
import { forwardRef, Type } from '@angular/core'; | |
/** | |
* Function to create the basic provider to components which use `ngModel` as required by Angular. | |
* @param type component type which extends `SimpleControlValueAcessor` | |
*/ | |
export function createProviders(type: Type<SimpleControlValueAcessor>) { | |
return [ | |
{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => type), multi: true } | |
]; | |
} | |
/** | |
* Base class to create components that use `ngModel` and just need a simple getter/setter. | |
* In case where a more complex getter/setter is required, just create one in the component and call | |
* this one. | |
*/ | |
export class SimpleControlValueAcessor implements ControlValueAccessor { | |
private _value: string; | |
private onChange: any = (_: any) => { }; | |
private onTouched: any = () => { }; | |
public get value() { | |
return this._value; | |
} | |
public set value(val: string) { | |
if (this._value === val) return; | |
this._value = val; | |
this.onChange(val); | |
this.onTouched(); | |
} | |
registerOnChange(fn) { | |
this.onChange = fn; | |
} | |
registerOnTouched(fn) { | |
this.onTouched = fn; | |
} | |
writeValue(value) { | |
this.value = value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment