Skip to content

Instantly share code, notes, and snippets.

@armanozak
Last active May 9, 2019 08:24
Show Gist options
  • Save armanozak/f16365d279143195e76fccf27590fc32 to your computer and use it in GitHub Desktop.
Save armanozak/f16365d279143195e76fccf27590fc32 to your computer and use it in GitHub Desktop.
A Sample Component with a Value Accessible via FormControlName, FormControlDirective or NgModel Directives #blog
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { Component, forwardRef, Input } from '@angular/core';
@Component({
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => SampleComponent),
multi: true,
}],
/* Rest is removed for brevity */
})
export class SampleComponent implements ControlValueAccessor {
@Input()
disabled: boolean;
@Input()
set value(value: string) {
this._value = value;
this.notifyValueChange();
}
get value(): string{
return this._value;
}
onChange: (value: string) => {};
onTouched: () => {};
private _value: string;
notifyValueChange(): void {
if (this.onChange) {
this.onChange(this.value);
}
}
writeValue(value: string): void {
this._value = value;
}
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