加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 如何在ngFor(嵌套formArray)中访问ngFor中的formCont

发布时间:2020-12-17 17:11:19 所属栏目:安全 来源:网络整理
导读:我是Angular 2的初学者.我正在尝试创建一个具有动态表单的表,创建表并且值也绑定但是我无法访问formControlName中的值,尝试下面的代码但它不起作用. 有人可以帮助我在下面的代码我做错了 HTML tbody formArrayName="timetable" tr *ngFor="let child of time
我是Angular 2的初学者.我正在尝试创建一个具有动态表单的表,创建表并且值也绑定但是我无法访问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,day:'Tuesday'
                        }),day:'Wednesday'
                        }),day:'Thursday'
                        }),day:'Friday'
                        })
                    ])
                }),this.formBuilder.group({
                    periods: this.formBuilder.array([
                        this.formBuilder.group({
                            subject_id:10,name:'Thursday'
                        })
                    ])
                })
            ])
         });

提前致谢.

解决方法

我注意到的第一件事

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

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

第三,你应该使用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读