框架:angular8
UI: NG-ZORRO 7.5
问题: 当nz-select框为多选nzMode="multiple"
,nz-select
所传[nzValue]
值为对象时,此时默认值ngModel
不显示,选中一个选项后页面可显示。
代码:
<nz-select name="program" nzMode="multiple"
[nzMaxMultipleCount]="3"
[nzMaxTagPlaceholder]="programPlaceHolder"
[(ngModel)]="policy['program']['data']"
nzPlaceHolder="请选择应用程序策略">
<nz-option *ngFor="let option of policy['program']['list']" [nzLabel]="option.name [nzValue]="option">
</nz-option>
<ng-template #programPlaceHolder let-selectedList>已选中 {{ policy['program'['data'].length}}项
</ng-template>
</nz-select>
注:若policy['program']['data']值为{name:"111", id:1},页面无法select选中内容无法回显
解决: ngModel
取到的值为选中 nz-option
的 nzValue
值,当 nzValue
传入为一个对象时,ngModel
获取的值也是一个对象,此时[compareWith]="compareFn",comparwith用法见这里
代码改进:
html:
<nz-select name="program" nzMode="multiple"
[compareWith]="compareFn"
[nzMaxMultipleCount]="3"
[nzMaxTagPlaceholder]="programPlaceHolder"
[(ngModel)]="policy['program']['data']"
nzPlaceHolder="请选择应用程序策略">
<nz-option *ngFor="let option of policy['program']['list']" [nzLabel]="option.name [nzValue]="option">
</nz-option>
<ng-template #programPlaceHolder let-selectedList>已选中 {{ policy['program'['data'].length}}项
</ng-template>
</nz-select>
ts:
// 解决select value值为对象,select默认值不展示问题
compareFn = (o1: any, o2: any) => (o1 && o2 ? o1.name === o2.name : o1 === o2);