我正在尝试按照 this article 向我的表单添加一个 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
答案 0 :(得分:0)
IDK 如何正确修复此错误(我通过研究我自己遇到的这个问题遇到了您的问题),这是我摆脱它的方法:
在 tsconfig.json 文件中删除 strictTemplates
的 angularCompilerOptions
选项或将其设置为 false:
...
,
"angularCompilerOptions": {
"strictTemplates": false
}
答案 1 :(得分:0)
您需要为组件模型添加更强的类型。
您可以将 AbstractControl
转换为 FormControl
并创建对 devices.controls
的引用
然后您可以创建一个获取 FormControl
而不是 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)">
答案 2 :(得分:0)
因为它不是禁用整个字符串模板的好解决方案,因为它对我来说是跟踪错误的有用功能。在您的情况下,您可以为此 formControl 输入 [formControl]="$any(formControl)" 或 [formControl]="$any(devices.controls[i])" 使用任何强制转换。
在我的例子中,错误是由抽象的 FieldType 引起的。
只读 formControl: import("@angular/forms").AbstractControl;
[编辑] 这应该只是一个临时的解决方法,直到严格的模板检查按预期工作。