Angular循环FormArray条件显示报错,需展示is_dependent_exist=0的字段
问题解决:Angular FormArray根据字段控制显示与隐藏及报错修复
错误原因
你遇到的Property 'c' does not exist错误,核心原因是Angular不允许同一个DOM元素上绑定多个结构型指令(*ngFor和*ngIf都属于结构型指令),这会导致索引变量c的作用域冲突,*ngIf无法访问到*ngFor定义的c变量。
解决方案
提供两种可行方案,按需选择:
方案1:提前在组件中过滤数据(推荐)
这种方式更简洁,避免模板中索引匹配出错,同时减少模板逻辑:
组件类中处理数据
在组件的ngOnInit或合适的生命周期钩子中,过滤出is_dependent_exist为0的字段,同时同步更新FormArray的控件:// 组件类代码 all_user_custom_fields = [ { 'field_name_slug': 'radio_button_with_group_custom_field8', 'is_dependent_exist': 0 }, { 'field_name_slug': 'radio_button_with_default_value', 'is_dependent_exist': 1 }, { 'field_name_slug': 'radio_button_with_mandatory', 'is_dependent_exist': 1 }, { 'field_name_slug': 'check_box_with_mandatory', 'is_dependent_exist': 0 } ]; filteredCustomFields: any[]; custom_field_dataArray: FormArray; ngOnInit() { // 过滤出需要显示的字段 this.filteredCustomFields = this.all_user_custom_fields.filter(field => field.is_dependent_exist === 0); // 重新构建FormArray,只包含过滤后的字段对应的控件 this.custom_field_dataArray = new FormArray( this.filteredCustomFields.map(field => { // 根据你的需求设置初始值和验证器 return new FormControl(''); }) ); // 如果是嵌套在父FormGroup中,记得把FormArray加入父表单 // this.parentForm.addControl('customFields', this.custom_field_dataArray); }模板代码修改
直接遍历过滤后的数组,无需额外判断:<ng-container *ngFor="let field of filteredCustomFields; index as c;"> <div [formGroupName]="c" class="col-12 md:col-6 lg:col-4"> <input formControlName="{{field.field_name_slug}}" type="text" (keyup)="validate($event, c, field.field_name_slug)" pInputText /> </div> </ng-container>
方案2:使用ng-container分离结构指令(模板层面处理)
如果不想修改组件数据逻辑,可以用ng-container承载*ngFor,在内部div使用*ngIf判断:
<ng-container *ngFor="let CustomUser of custom_field_dataArray.controls; index as c;"> <div [formGroupName]="c" class="col-12 md:col-6 lg:col-4" *ngIf="all_user_custom_fields[c]?.is_dependent_exist === 0" > <input formControlName="{{all_user_custom_fields[c]?.field_name_slug}}" type="text" (keyup)="validate($event, c, all_user_custom_fields[c]?.field_name_slug)" pInputText /> </div> </ng-container>
ng-container是Angular提供的虚拟容器,不会渲染成真实DOM元素,专门用来承载结构型指令,完美解决多个结构指令的冲突问题。
内容的提问来源于stack exchange,提问作者Anil Kumar Boddu
相关产品推荐
相关产品推荐

