ControlValueAccessor

A ControlValueAccessor acts as a bridge between the Angular forms API and a native element in the DOM.

interface ControlValueAccessor { writeValue(obj: any): void registerOnChange(fn: any): void registerOnTouched(fn: any): void setDisabledState(isDisabled: boolean)?: void }

说明

Implement this interface if you want to create a custom form control directive that integrates with Angular forms.

方法

Writes a new value to the element.

writeValue(obj: any): void

参数

obj

Type: any.

返回值

void

This method will be called by the forms API to write to the view when programmatic (model -> view) changes are requested.

Example implementation of writeValue:

writeValue(value: any): void { this._renderer.setProperty(this._elementRef.nativeElement, 'value', value); }

Registers a callback function that should be called when the control's value changes in the UI.

registerOnChange(fn: any): void

参数

fn

Type: any.

返回值

void

This is called by the forms API on initialization so it can update the form model when values propagate from the view (view -> model).

If you are implementing registerOnChange in your own value accessor, you will typically want to save the given function so your class can call it at the appropriate time.

registerOnChange(fn: (_: any) => void): void { this._onChange = fn; }

When the value changes in the UI, your class should call the registered function to allow the forms API to update itself:

host: { (change): '_onChange($event.target.value)' }

Registers a callback function that should be called when the control receives a blur event.

registerOnTouched(fn: any): void

参数

fn

Type: any.

返回值

void

This is called by the forms API on initialization so it can update the form model on blur.

If you are implementing registerOnTouched in your own value accessor, you will typically want to save the given function so your class can call it when the control should be considered blurred (a.k.a. "touched").

registerOnTouched(fn: any): void { this._onTouched = fn; }

On blur (or equivalent), your class should call the registered function to allow the forms API to update itself:

host: { '(blur)': '_onTouched()' }

This function is called by the forms API when the control status changes to or from "DISABLED". Depending on the value, it should enable or disable the appropriate DOM element.

setDisabledState(isDisabled: boolean)?: void

参数

isDisabled

Type: boolean.

返回值

void

Example implementation of setDisabledState:

setDisabledState(isDisabled: boolean): void { this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled); }