Skip to content

Instantly share code, notes, and snippets.

@wesleyegberto
Created September 9, 2019 23:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wesleyegberto/94b0b814debcbe283c115a76bb975104 to your computer and use it in GitHub Desktop.
Save wesleyegberto/94b0b814debcbe283c115a76bb975104 to your computer and use it in GitHub Desktop.
Base class to create Angular components
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