Angular中如何用*ngFor在p-dropdown的optionLabel拼接两个属性?
解决方案:将mat-select转换为PrimeNG p-dropdown实现属性拼接显示
针对你的需求,这里提供两种实现方式,都能实现把referenceId和officeName拼接后作为选项显示,同时将referenceId作为选项值绑定到表单控件:
方法1:预处理数据(推荐复用场景)
先在组件类中给每个办公对象添加一个拼接好的显示字段,再绑定到p-dropdown的optionLabel:
组件代码(.ts)
// 预处理办公数据,添加拼接后的显示标签 processedOffices = this.worldAreaSpecifcOffices.map(office => ({ ...office, displayLabel: `${office.referenceId} - ${office.officeName}` }));
模板代码(.html)
<label for="Pricing Office ID"> Pricing Office ID</label> <p-dropdown class="custom-dropdown" name="pricingOfficeID" formControlName="pricingOfficeID" [options]="processedOffices" optionLabel="displayLabel" optionValue="referenceId" (onChange)="changePricingOfficeID()" ></p-dropdown>
方法2:使用ng-template自定义选项(无需修改原始数据)
直接在模板中通过ng-template自定义选项的显示内容,不需要预处理数据:
模板代码(.html)
<label for="Pricing Office ID"> Pricing Office ID</label> <p-dropdown class="custom-dropdown" name="pricingOfficeID" formControlName="pricingOfficeID" [options]="worldAreaSpecifcOffices" optionValue="referenceId" (onChange)="changePricingOfficeID()" > <ng-template let-office pTemplate="item"> {{office.referenceId}} - {{office.officeName}} </ng-template> </p-dropdown>
关键说明
optionValue="referenceId"对应原mat-select中[value]="office.referenceId"的逻辑,确保表单控件绑定的是referenceId值- 事件绑定从mat-select的
selectionChange改为p-dropdown的onChange事件 - 表单赋值时,直接给
pricingOfficeID控件赋值对应的referenceId即可,逻辑和原mat-select完全一致
内容的提问来源于stack exchange,提问作者Ashok C Vaithinathan
相关产品推荐
相关产品推荐

