Created
July 19, 2017 12:55
-
-
Save dmorosinotto/4100c3ad958b489cec7b0b5a059936b3 to your computer and use it in GitHub Desktop.
Abastract VALUE used to custom component for Forms (implementing ControlValueAccessor)
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
// Code inspired by http://www.anasfirdousi.com/share-controlvalueaccessor-provider-creation-with-abstract-controlvalueaccessor-across-custom-form-enabled-angular-components.html | |
import { Component, Directive, Provider, forwardRef, Type } from '@angular/core'; | |
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; | |
export abstract class AbstractValueAccessor<T> implements ControlValueAccessor { | |
private _value: T = ''; | |
public get value(): T { return this._value; }; | |
public set value(v: T) { | |
if (v !== this._value) { | |
this._value = v; | |
this.onChange(v); | |
} | |
} | |
protected onChange = (_) => {}; | |
protected onTouched = () => {}; | |
// ControlValueAccessor implementation | |
private writeValue(value: T) { | |
console.log('wrrite value', value); | |
this._value = value; | |
this.onChange(value); | |
} | |
private registerOnChange(fn: (_: any) => void): void { this.onChange = fn; } | |
private registerOnTouched(fn: () => void): void { this.onTouched = fn; } | |
} | |
export function MakeProvider(typeCustomCmpClass : any){ | |
return { | |
provide: NG_VALUE_ACCESSOR, | |
useExisting: forwardRef(() => typeCustomCmpClass), | |
multi: true | |
}; | |
} | |
/* | |
// USAGE in your CustomCmp extends AbstractValueAccessor<TYPE_OF_YOUR_VALUE> + use value in the template and bind/call onTouch/onChange | |
@Component({ | |
selector: 'custom-range', | |
template:` | |
<div class="custom-range"> | |
{{ label }} | |
<input type="range" min=0 max=500 [(ngModel)]="value" (input)="onChange($event.target.value)" /> {{ value }} | |
</div> | |
` | |
providers: [ MakeProvider(CustomRange) ] | |
}) | |
export class CustomRange extends AbstractValueAccessor<number> { | |
@Input() label: string; | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment