gpt4 book ai didi

angular - 如何在 ngFor(嵌套的 formArray)中访问 ngFor 中的 formControlName?

转载 作者:太空狗 更新时间:2023-10-29 17:58:33 27 4
gpt4 key购买 nike

我是 Angular 2 的初学者。我正在尝试创建一个具有动态表单的表,创建了表并且还绑定(bind)了值但是我无法访问 formControlName 中的值,尝试了下面的代码但它没有用。

有人可以帮助我在下面的代码中做错的地方

HTML

<tbody formArrayName="timetable">
<tr *ngFor="let child of timetableForm.controls.timetable.controls; let i = index;" [formGroupName]="i">
<td *ngFor="let period of child.controls.periods.controls;let j = index;" [formGroupName]="j">
{{period.controls.day.value}} <!-- bind is working fine -->
<input type="text" [formControlName]="day"> <!-- error -->
</td>
</tr>
</tbody>

TS

ngOnInit(){
this.tableForm = this.formBuilder.group({
timetable: this.formBuilder.array([
this.formBuilder.group({
periods: this.formBuilder.array([
this.formBuilder.group({
subject_id:10,
timing_id:11,
day:'Monday'
}),
this.formBuilder.group({
subject_id:10,
timing_id:11,
day:'Tuesday'
}),
this.formBuilder.group({
subject_id:10,
timing_id:11,
day:'Wednesday'
}),
this.formBuilder.group({
subject_id:10,
timing_id:11,
day:'Thursday'
}),
this.formBuilder.group({
subject_id:10,
timing_id:11,
day:'Friday'
})
])
}),
this.formBuilder.group({
periods: this.formBuilder.array([
this.formBuilder.group({
subject_id:10,
timing_id:11,
day:'Monday'
}),
this.formBuilder.group({
subject_id:10,
timing_id:11,
day:'Tuesday'
}),
this.formBuilder.group({
subject_id:10,
timing_id:11,
day:'Wednesday'
}),
this.formBuilder.group({
subject_id:10,
timing_id:11,
name:'Thursday'
})
])
})
])
});

提前致谢。

最佳答案

我首先注意到的是

this.formBuilder.group({
subject_id:10,
timing_id:11,
name:'Thursday'
^^^^
it should be day
})

其次,为什么在模板中使用 timetableForm 而在组件中创建 tableForm

第三,您应该使用 formControlName="day" 而不是评论中提到的 [formControlName]="day"

最后,您忘记了将子数组包装在 formArrayName="periods" 中。为此,您可以使用 ng-container,如下所示:

<table [formGroup]="tableForm">
<tbody formArrayName="timetable">
<tr *ngFor="let child of tableForm.controls.timetable.controls; let i = index;" [formGroupName]="i">
<ng-container formArrayName="periods">
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
add this
<td *ngFor="let period of child.controls.periods.controls;let j = index;" [formGroupName]="j">
{{period.controls.day.value}}
<input type="text" formControlName="day">
</td>
</ng-container>
</tr>
</tbody>
</table>

Ng-run Example

关于angular - 如何在 ngFor(嵌套的 formArray)中访问 ngFor 中的 formControlName?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49962153/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com