Angular如何仅当对应id的template_parameter有值时显示动态表单
解决方案
第一步:修改TS逻辑
首先在组件类中新增一个控制表单显隐的布尔变量,同时修正changeSelection方法里的逻辑(你原代码在filter回调里push数据会导致重复选中,同步加非空判断):
// 组件类中先声明变量 public showTemplateForm: boolean = false; changeSelection() { this.selectedItemsList = this.DisplayProductList.filter(product => product.isChecked); // 取当前选中项的template_parameter,此处默认是单选逻辑,如果是多选你可以按需调整取值逻辑 if (this.selectedItemsList.length > 0) { const currentParam = this.selectedItemsList[0].template_parameter; // 判断是否为有效值,排除null、字符串"null"、空值的情况 if (currentParam && currentParam !== 'null') { const sepratedArray = currentParam.split(','); this.variable1 = sepratedArray[0]; this.variable2 = sepratedArray[1]; this.showTemplateForm = true; // 启用表单控件 this.templateform.get('namespace')?.enable(); this.templateform.get('resource')?.enable(); } else { this.showTemplateForm = false; // 禁用表单控件,避免隐藏时触发必填校验 this.templateform.get('namespace')?.disable(); this.templateform.get('resource')?.disable(); } } else { this.showTemplateForm = false; this.templateform.get('namespace')?.disable(); this.templateform.get('resource')?.disable(); } }
第二步:修改HTML模板
给需要隐藏的表单部分外层加*ngIf判断,绑定上面定义的showTemplateForm变量即可:
<form [formGroup]="templateform"> <!-- 仅当showTemplateForm为true时显示下面的表单项 --> <ng-container *ngIf="showTemplateForm"> <div class="form-group"> <label for="ntw-pol-egren-podns" class="bmd-label-floating">{{variable1}}<sup class="text-danger">*</sup> </label> <input [(ngModel)]="namespace" formControlName="namespace" type="text" class="form-control" id="ntw-pol-egren-podns"> <div *ngIf="submitted && f.namespace.errors" class="error-feedback error"> <p *ngIf="f.namespace.errors.required" class="text-danger"> Namespace is required </p> </div> </div> <div class="form-group"> <label for="ntw-pol-egren-resource" class="bmd-label-floating">{{variable2}}<sup class="text-danger">*</sup></label> <input type="text" class="form-control" formControlName="resource" [(ngModel)]="resources" id="ntw-pol-egren-resource"> <div *ngIf="submitted && f.resource.errors" class="error-feedback error"> <p *ngIf="f.resource.errors.required" class="text-danger "> Resource is required </p> </div> </div> <div class="d-flex justify-content-end"> <button (click)="sendclusteridApi()" class="btn btn-primary px-3 py-2">Save</button> </div> </ng-container> </form>
补充说明:你原有代码中两个input的id重复了,已将第二个的id修改为ntw-pol-egren-resource,避免DOM id冲突
内容的提问来源于stack exchange,提问作者Mercy
相关产品推荐
相关产品推荐

