我有一个实现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
。
答案 0 :(得分:1)
您是否尝试过@SkipSelf()而不是@Self()?
答案 1 :(得分:0)
您可以尝试以下方法:
constructor(private injector: Injector) {
}
ngDoCheck() {
let ngControl = this.injector.get(NgControl);
if (! ngControl.control) {
return;
}
this.touched = ngControl.control.touched;
}