【问题标题】:Angular 2 Custom Form Component: Provide a markTouched methodAngular 2 自定义表单组件:提供 markTouched 方法
【发布时间】:2017-09-18 13:38:24
【问题描述】:

我有一个实现 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()

我找不到这样做的角度方式。

@编辑: 尝试注入 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


    【解决方案1】:

    您是否尝试过@SkipSelf() 而不是@Self()?

    【讨论】:

    • 没有抛出异常,但是没有接收到注入的控件
    【解决方案2】:

    你可以试试这个:

    constructor(private injector: Injector) {
    }
    
    
    ngDoCheck() {
    
        let ngControl = this.injector.get(NgControl);
        if (! ngControl.control) {
            return;
        }
    
        this.touched = ngControl.control.touched;
    
    }
    
    
    

    【讨论】:

      【解决方案3】:

      循环依赖是由 NG_VALUE_ACCESSOR 在您的 @Component(...) 提供程序中以及在构造函数中注入 NgControl 引起的。这些是相互排斥的。

      在此处查看 NG 材料文档中的示例:https://material.angular.io/guide/creating-a-custom-form-field-control#ngcontrol

      【讨论】:

        猜你喜欢
        • 2016-06-27
        • 1970-01-01
        • 2017-03-02
        • 2018-04-26
        • 2016-12-17
        • 2017-06-11
        • 2016-04-29
        • 1970-01-01
        • 2019-05-29
        相关资源
        最近更新 更多