2016-10-31 6 views
0

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

Antwort

2

Sie haben benutzerdefinierte bieten NG_VALUE_ACCESSOR wie:

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 { 

http://plnkr.co/edit/VEWs1n8kbWs7riacSVu3?p=preview

+0

Danke, es funktioniert. – cebor

Verwandte Themen