我有一个包装表单控件输入字段的组件,为此我正在尝试实现ControlValueAccessor
。
但是我没有让它发挥作用。
定制input.component.ts:
import { Component, Input } from '@angular/core';
import { ControlValueAccessor, FormGroup } from '@angular/forms';
const noop = () => {};
@Component({
selector: 'custom-input',
template: '<input [(ngModel)]="value" (blur)="onBlur()">{{value}}'
})
export class CustomInputComponent implements ControlValueAccessor {
private onTouchedCallback: () => void = noop;
private onChangeCallback: (_: any) => void = noop;
private _value: any = '';
get value() {
return this._value;
}
set value(v: any) {
if (v !== this._value) {
this._value = v;
this.onChangeCallback(v);
}
}
onBlur() {
this.onTouchedCallback();
}
writeValue(value: any): void {
this._value = value;
}
registerOnChange(fn: any): void {
this.onChangeCallback = fn;
}
registerOnTouched(fn: any): void {
this.onTouchedCallback = fn;
}
}
我这样用它:
<custom-input [(ngModel)]="foo"></custom-input>
例外:
No value accessor for form control with unspecified name attribute
Angular Verion:2.1.2
答案 0 :(得分:2)
您必须提供自定义NG_VALUE_ACCESSOR
,如:
export const TEST_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => TestComponent),
multi: true
};
@Component({
selector: 'test',
template: '<input [(ngModel)]="value" (blur)="onBlur()">{{value}}',
providers: [TEST_VALUE_ACCESSOR] // <== this line
})
export class TestComponent implements ControlValueAccessor {