angular - 角度错误 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
解决方案
您将需要为组件模型添加更强的类型。您可以转换AbstractControl
asFormControl
并创建对的引用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)">
推荐阅读
- c++ - 无法在 Visual Studio 中创建 C++ 项目
- ios - 如何处理重量转换
- google-chrome - Chart.JS 不渲染和显示悲伤的脸图标
- node.js - 如何使用数据库PG POOL的正确方法是什么
- dart - 什么是 Dart 语言中 JSON 的头库
- python - Matplotlib 绘图绘制直线,不显示正确的 y 值
- php - 更新/插入一次然后退出
- php - 关系在 Laravel Tinker 中有效,但不在控制器中
- reactjs - 反应本机 - FETCH - 授权标头不起作用
- jsf - adf addpartialTarget 未正确呈现 UI 组件