首页 > 解决方案 > 角度错误 TS2739:“AbstractControl”类型缺少“FormControl”类型的以下属性

问题描述

在本文之后,我正在尝试将 formArray 添加到我的表单中。我得到的错误粘贴在底部,似乎是[formControl]="devices.controls[i]"输入的问题。该错误使我无法为我的应用程序提供服务,但我无法弄清楚它有什么问题。

HTML

<div formArrayName="devices">
    <h3>Devices</h3>
    <button (click)="addDevice()">Add Device</button>

    <div *ngFor="let control of devices.controls; index as i">
        <label>
            Device:
            <input type="text" [formControl]="devices.controls[i]">
        </label>
    </div>
</div>

TS

terminalNameInput = new FormControl();
devices = new FormArray([]);

addTerminalGroup = new FormGroup({
    terminalNameInput : this.terminalNameInput,
    devices : this.devices,
});

addDevice() {
    this.devices.push(new FormControl(''));
}

完全错误

错误 TS2739:“AbstractControl”类型缺少“FormControl”类型的以下属性:registerOnChange、registerOnDisabledChange、_applyFormState

标签: angulartypescriptangular-reactive-forms

解决方案


您将需要为组件模型添加更强的类型。您可以转换AbstractControlasFormControl并创建对的引用devices.controls 然后您可以创建一个获取 aFormControl而不是AbstractControl

您可以通过component.ts如下更改来做到这一点


addTerminalGroup: FormGroup;
get terminalNameInput(): FormControl { this.addTerminalGroup.controls.terminalNameInput as FormControl }
get devices(): FormArray { this.addTerminalGroup.controls.devices as FormArray }

constructor(private formBuilder:FormBuilder){
    this.addTerminalGroup = this.formBuilder.group({
        terminalNameInput : new FormControl('', []),
        devices : new FormArray(),
    });
}

addDevice() {
    this.devices.push(new FormControl(''));
}

// Used to get a strongly typed FormControl
getDeviceByIndex(index: number): FormControl {
    return this.devices.at(index) as FormControl;
}

然后在你的component.html你可以更换

<input type="text" [formControl]="devices.controls[i]">

与以下

<input type="text" [formControl]="getDeviceByIndex(i)">

推荐阅读