Ich habe eine Komponente, die ein Formularsteuerfeld eingibt, für das ich versuche, das ControlValueAccessor
zu implementieren.Benutzerdefiniertes Steuerelement: ControlValueAccessor funktioniert nicht
Aber ich bekomme es nicht funktioniert.
custom-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;
}
}
und ich verwende es wie folgt aus:
<custom-input [(ngModel)]="foo"></custom-input>
Ausnahme:
No value accessor for form control with unspecified name attribute
Angular Verion 2.1. 2
Plunker: http://plnkr.co/edit/PgL81hTMdwJpPUs4wOOU?p=preview
Danke, es funktioniert. – cebor