Angular 10 严格模式:AbstractControl 与 FormControl

Wol*_*359 5 angular angular-reactive-forms

我有这个自定义组件:

<my-component [control]="..."></my-component>
Run Code Online (Sandbox Code Playgroud)

这里,控制定义为:

@Input() control: FormControl;
Run Code Online (Sandbox Code Playgroud)

我的组件的用法:

this.myFormGroup = new FormGroup({
    name: new FormControl('')
});

<my-component [control]="myFormGroup.controls.name"></my-component>
Run Code Online (Sandbox Code Playgroud)

错误:

Angular 10 严格模式抱怨“myFormGroup.controls.name”不是一个 FormControl。

“控件”在 FormGroup 中定义为一个对象,其中每个字段都是 AbstractControl 类型:

// forms.d.ts
export declare class FormGroup extends AbstractControl {
    controls: {
        [key: string]: AbstractControl;
    };
    // ....
}
Run Code Online (Sandbox Code Playgroud)

这段代码可以在运行时运行,但不能编译。

解决这个问题的最佳方法是什么?

Mic*_*ael 2

我过去通过在表单组之外保留对表单控件的引用来避免这种情况。

例如:

this.nameControl = new FormControl()
this.myFormGroup = new FormGroup({
    name: this.nameControl,
});
Run Code Online (Sandbox Code Playgroud)