Last active
May 9, 2019 08:24
-
-
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
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 { 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