Angular中如何将参数拆分至两个文本框作标签,勾选复选框后如何在HTML展示
调整方案
1. 现有代码问题梳理
- 分隔符使用错误:后端返回的
template_parameter是逗号分隔的字符串,你当前使用空格作为拆分依据,无法得到正确的拆分结果 - 逻辑位置错误:
filter方法仅负责筛选选中项,不要将字段拆分的业务逻辑写在筛选逻辑中
2. TS代码修改
changeSelection(event: any) { // filter仅保留筛选逻辑,过滤出所有选中的商品 this.selectedItemsList = this.DisplayProductList.filter(product => product.isChecked); } // 新增拆分参数的公共方法,兼容空值避免报错 splitTemplateParam(paramStr: string): string[] { return paramStr ? paramStr.split(',') : ['', '']; }
3. HTML模板修改
直接在模板中调用拆分方法,渲染两个文本框:
<div class="pb-3 pl-3" *ngFor="let product of selectedItemsList"> <h4 class="fw-500 fw-b"> <a (click)="openCaseDetails(product.id)">{{ product.template_parameter}}</a> </h4> <div class="mt-2"> <input type="text" [value]="splitTemplateParam(product.template_parameter)[0]" class="mr-2"> <input type="text" [value]="splitTemplateParam(product.template_parameter)[1]"> </div> </div>
可选优化方案
如果不想在模板中重复调用拆分方法,可以在筛选时直接把拆分后的参数挂载到商品对象上:
changeSelection(event: any) { this.selectedItemsList = this.DisplayProductList .filter(product => product.isChecked) .map(product => { const params = product.template_parameter?.split(',') || ['', '']; return { ...product, paramFirst: params[0], paramSecond: params[1] }; }); }
模板直接使用挂载后的属性即可:
<input type="text" [value]="product.paramFirst" class="mr-2"> <input type="text" [value]="product.paramSecond">
内容的提问来源于stack exchange,提问作者Mercy
相关产品推荐
相关产品推荐

