角度错误 TS2739:类型“AbstractControl”缺少类型“FormControl”中的以下属性

daw*_*777 2 typescript angular angular-reactive-forms

我正在尝试按照本文添加一个 formArray 到我的表单中。我收到的错误粘贴在底部,似乎是[formControl]="devices.controls[i]"输入问题。该错误阻止我提供应用程序服务,但我无法弄清楚它出了什么问题。

超文本标记语言

<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>
Run Code Online (Sandbox Code Playgroud)

TS

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

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

addDevice() {
    this.devices.push(new FormControl(''));
}
Run Code Online (Sandbox Code Playgroud)

完全错误

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

Sha*_*ane 6

您将需要向组件模型添加更强的类型。您可以将您的AbstractControlas转换FormControl为并创建对的引用然后您可以创建一个获取 a而不是的devices.controls 方法FormControlAbstractControl

您可以通过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;
}

Run Code Online (Sandbox Code Playgroud)

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

<input type="text" [formControl]="devices.controls[i]">
Run Code Online (Sandbox Code Playgroud)

与以下

<input type="text" [formControl]="getDeviceByIndex(i)">
Run Code Online (Sandbox Code Playgroud)