Created
October 14, 2019 16:24
-
-
Save angelo510/60cbc77e10e9a39dc8c851faa7e60cd4 to your computer and use it in GitHub Desktop.
BaseFieldComponent with ControlValueAccessor for global field definition
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 { EventEmitter, Input, Output } from "@angular/core"; | |
import { ControlValueAccessor } from "@angular/forms"; | |
import { parseBooleanAttribute } from "src/utils"; | |
export abstract class BaseFieldComponent<T> implements ControlValueAccessor { | |
@Input() public fieldId?: string; | |
@Input() public label?: string; | |
@Input() public description?: string; | |
@Input() public value: T | null = null; | |
@Input() public set disabled(value: boolean | string | undefined) { | |
this.isDisabled = parseBooleanAttribute(value); | |
} | |
public isDisabled = false; | |
@Input() public set readonly(value: boolean | string | undefined) { | |
this.isReadonly = parseBooleanAttribute(value); | |
} | |
public isReadonly = false; | |
@Output() public readonly change = new EventEmitter<T>(); | |
private formOnChangeCallback?: (value: T) => void; | |
private formOnTouchedCallback?: () => void; | |
public onChange(value: T): void { | |
this.value = value; | |
this.change.emit(value); | |
if (this.formOnChangeCallback) { | |
this.formOnChangeCallback(value); | |
} | |
} | |
public onBlur(): void { | |
if (this.formOnTouchedCallback) { | |
this.formOnTouchedCallback(); | |
} | |
} | |
public writeValue(value: T): void { | |
this.value = value; | |
} | |
public registerOnChange(fn: (value: T) => void): void { | |
this.formOnChangeCallback = fn; | |
} | |
public registerOnTouched(fn: () => void): void { | |
this.formOnTouchedCallback = fn; | |
} | |
public setDisabledState(isDisabled: boolean): void { | |
this.isDisabled = isDisabled; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment