Angular2自定义组件按钮无法连接到外部表单

时间:2016-11-11 02:01:23

标签: angular angular2-forms

我有一个问题。

我的自定义组件有一个重置formControlName的按钮,但它不起作用。 我的自定义组件值是rest,但此值不连接到formControlName。

例如:https://plnkr.co/edit/r6BBF3?p=preview

我的自定义组件:



export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => CustomInputComponent),
    multi: true
};

@Component({
    selector: 'custom-input',
    template: `<div class="form-group">
                    <label><ng-content></ng-content>
                        <input [(ngModel)]="value"  
                                class="form-control" 
                                (blur)="onBlur()" >
                    </label>
                    <button type="button" (click)="clear()">clear</button>
                </div>`,
    providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class CustomInputComponent implements ControlValueAccessor {

    private innerValue: any = '';
    private onTouchedCallback: () => void = noop;
    private onChangeCallback: (_: any) => void = noop;

    //get accessor
    get value(): any {
        return this.innerValue;
    };

    //set accessor including call the onchange callback
    set value(v: any) {
        if (v !== this.innerValue) {
            this.innerValue = v;
            this.onChangeCallback(v);
        }
    }

    //Set touched on blur
    onBlur() {
        this.onTouchedCallback();
    }
    
    clear(){
       this.innerValue = '';
    }

    //From ControlValueAccessor interface
    writeValue(value: any) {
        if (value !== this.innerValue) {
            this.innerValue = value;
        }
    }

    //From ControlValueAccessor interface
    registerOnChange(fn: any) {
        this.onChangeCallback = fn;
    }

    //From ControlValueAccessor interface
    registerOnTouched(fn: any) {
        this.onTouchedCallback = fn;
    }

}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

试试这个

clear(){
   this.innerValue = '';
   this.onChangeCallback('');
}

分叉工作Plunker