gpt4 book ai didi

angular2-forms - Angular 2 自定义表单组件 : Provide a markTouched method

转载 作者:行者123 更新时间:2023-12-02 03:04:41 25 4
gpt4 key购买 nike

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

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()

我找不到一个有角度的方式来做到这一点。

@编辑:试图注入(inject) 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;
}

}

但我得到 无法实例化循环依赖! NgControl 当使用 formControl 调用组件时。

最佳答案

你试过用@SkipSelf()代替@Self()吗?

关于angular2-forms - Angular 2 自定义表单组件 : Provide a markTouched method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43544607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com