“ AbstractControl”类型的角度4上不存在属性“ control”

我正在尝试在角度4嵌套反应形式。它工作得很好,但是当我尝试构建 AOT 时,它抛出了错误

'controls' does not exist on type 'AbstractControl'

我在谷歌上搜索并尝试了一些东西,但没有任何收获。有人能告诉我如何解决这个问题吗?

<div [formGroup]="myForm">
<div formArrayName="addresses">
<div *ngFor="let address of myForm.get('addresses').controls; let i=index"
class="panel panel-default">
<span *ngIf="myForm.get('addresses').length > 1"
(click)="removeAddress(i)">Remove</span>
<div [formGroupName]="i">
<mat-form-field>
<input matInput formControlName="city" placeholder="city" value="">
</mat-form-field>
</div>


</div>
</div>
<a (click)="addAddress()" style="cursor: default"> Add +</a>
</div>

下面的打印脚本代码

constructor(private _fb: FormBuilder) {
}


ngOnInit() {
this.myForm = this._fb.group({
addresses: this._fb.array([
this.initAddress(),
])
});
}
initAddress() {
return this._fb.group({
city: ['']
});
}
addAddress() {
const control = <FormArray>this.myForm.get('addresses');
control.push(this.initAddress());
}
removeAddress(i: number) {
const control = <FormArray>this.myForm.get('addresses');
control.removeAt(i);
}
135009 次浏览

要得到 FormArray的长度,只需使用 length:

<span *ngIf="myForm.controls['addresses'].length > 1" (click)="removeAddress(i)">Remove</span>

希望能有帮助

基于@G ünter Zöchbauer 的评论,首先我改变了

在 html 和类型脚本中从 myForm.controls['addresses']myForm.get('addresses')

然后基于@yuruzi 评论

myForm.get('addresses').controls改为 myForm.get('addresses')['controls']

现在工作正常。谢谢@gunter & yuruzi

Change myForm.get('addresses').controls to myForm.get('addresses').value will also fix the issue.

You can fix it easily though. Outsource the "get the controls" logic into a method of your component code (the .ts file):

getControls() {
return (this.recipeForm.get('controlName') as FormArray).controls;
}

In the template, you can then use:

*ngFor="let ingredientCtrl of getControls(); let i = index"

这个调整是必需的,因为 TS 的工作方式和角度解析您的模板(它不理解 TS 有)。

验证错误使用..。

<span *ngIf="f.YOUR_FORM_KEY.controls.YOUR_FORM_KEY.errors?.YOUR_FORM_VALIDATION">YOUR_FORM_KEY is YOUR_FORM_VALIDATION</span>

例如。

<span *ngIf="f.name.controls.name.errors?.required">Name is required</span>

文件

get f(): any {
return this.userForm.controls;
}

作为@sunny Kashyap 解决方案的一个更新,我会这样写:

getControls() {
return (this.recipeForm.get('controlName') as FormArray).controls;
}

可以使用自定义界面

// Define AbstractFormGroup
export interface AbstractFormGroup extends FormGroup {
controls: {
[key: string]: AbstractFormGroup & AbstractFormGroup[] & AbstractControl & FormGroup & FormArray,
}
}


// Usage example
class ... {
myForm: AbstractFormGroup
...
this.myForm = this.fb.group({...}) as AbstractFormGroup
}