Angular 2自定义表单组件:提供markTouched方法

问题描述 投票:2回答:2

我有一个实现ControlValueAccessor的自定义表单组件。该组件具有触及的内部属性。

export class BmInputComponent implements ControlValueAccessor, Validator {

    private onTouchedCallback: () => {};
    private touched: boolean = false;

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

    onBlur() {
        this.touched = true;
        this.onTouchedCallback();
    }
}

我需要实现一个类似的方法

markTouched() {
    this.touched = true;
}

当在formControl中执行markAsTouched时,组件的用户可以调用它:customInputControl.markAsTouched()

我无法找到一种方法来做到这一点。

@Edit:尝试注入NgControl:

@Component({
    selector: 'bm-input',
    templateUrl: './bm-input.component.html',
    encapsulation: ViewEncapsulation.None,
    providers: [
         {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => BmInputComponent),
            multi: true
        }
    ]
})
export class BmInputComponent implements ControlValueAccessor, Validator {

    private onTouchedCallback: () => {};
    private touched: boolean = false;

    constructor(@Self() @Optional() public _formControl: NgControl) {
        this._viewDate = new Date();
        if (this._formControl) {
            this._formControl.valueAccessor = this;
            this._formControl.statusChanges.subscribe(this.markTouched);
        }
    }
    registerOnTouched(fn: any) {
        this.onTouchedCallback = fn;
    }

    onBlur() {
        this.touched = true;
        this.onTouchedCallback();
    }

    markTouched() {
        if(this._formControl.touched)
            this.touched = true;
    }

}

但是当使用formControl调用组件时,我得到Cannot instantiate cyclic dependency! NgControl

angular2-forms angular2-custom-component
2个回答
1
投票

你试过@SkipSelf()而不是@Self()吗?


0
投票

你可以试试这个:

constructor(private injector: Injector) {
}


ngDoCheck() {

    let ngControl = this.injector.get(NgControl);
    if (! ngControl.control) {
        return;
    }

    this.touched = ngControl.control.touched;

}


© www.soinside.com 2019 - 2024. All rights reserved.