获取双嵌套形式数组的控件



我有一个工作代码。但Typescript抱怨道。

我有两个嵌套的表单数组(educationItem嵌套在education内(。我可以创建一个getter来访问第一个循环的FormArray控件。但是TypeScript并没有抱怨这个数组。

get controls(){
return (this.educationForm.get('education') as FormArray).controls
}

Typescript抱怨第二个数组,该数组嵌套在第一个数组中。TypeScript未将educationItem变量识别为FormArray。

getter函数不接受参数,我也不确定(1( 如何在模板中进行类型转换,或者(2( 编写一个以educationItem为参数的getter(可能是setter(

代码片段如下

<div *ngFor="let educationItem of education.controls; index as i">
<ng-container [formGroupName]="i">
<ng-container>
<ion-button type="button" (click)="addRole(educationItem)">Add Role</ion-button>
<div formArrayName="description">
<div
class="players"
*ngFor="let role of educationItem.get('description').controls; let roleIndex = index"
[formGroupName]="roleIndex"
>
<ion-item>
<ion-label position="floating">Role title</ion-label>
<ion-input formControlName="title"></ion-input>
</ion-item>
</div>
</div>
</ng-container>

</ng-container>
</div>

您不能使用getter,但可以使用函数。我无法想象你的json。如果我想象一些像:

educationForm={
education:[
{
description:[
{roleIndex:1,...rest of properties},
{roleIndex:2,...rest of properties},
],
...rest of properties
},
{
description:[
{roleIndex:1,...rest of properties},
{roleIndex:2,...rest of properties},
],
...rest of properties
}
],
...rest of properties
}

getDescription(index:number){
const group=(this.educationForm.get('education') as FormArray).at(index)
return (group.get('description') as FormArray)
}

使用$any((函数禁用模板中的类型检查。

试试这个:

<div *ngFor="let educationItem of education.controls; index as i">
<ng-container [formGroupName]="i">
<ng-container>
<ion-button type="button" (click)="addRole(educationItem)">Add Role</ion-button>
<div formArrayName="description">
<div
class="players"
*ngFor="let role of $any(educationItem).get('description').controls; let roleIndex = index"
[formGroupName]="roleIndex"
>
<ion-item>
<ion-label position="floating">Role title</ion-label>
<ion-input formControlName="title"></ion-input>
</ion-item>
</div>
</div>
</ng-container>
</ng-container>
</div>

最新更新