簡體   English   中英

Angular 2 自定義表單組件:提供一個 markTouched 方法

[英]Angular 2 Custom Form Component: Provide a markTouched method

我有一個實現 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;
    }

}

但我得到了Cannot instantiate cyclic dependency! NgControl Cannot instantiate cyclic dependency! NgControl當組件被調用與formControl。

你試過@SkipSelf() 而不是@Self() 嗎?

你可以試試這個:

constructor(private injector: Injector) {
}


ngDoCheck() {

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

    this.touched = ngControl.control.touched;

}


循環依賴是由在@Component(...)提供程序中同時具有NG_VALUE_ACCESSOR並在構造函數中注入NgControl的。 這些是相互排斥的。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM