Search code examples
htmljsonangularmulti-selectng-zorro-antd

Ng-Zorro select not showing selected items with NgModel


I am using Ng-Zorro's multiple select, which is in a drawer. When opening the drawer, I give the select element a list of options and a list of items that are already chosen. The list of options to pick from works fine, but the already selected items do not show. This can be seen here as well: StackBlitz

The code:

<nz-select [(ngModel)]="selectedAttributes"
                 [nzMaxTagCount]="3"
                 [nzMaxTagPlaceholder]="attributeTagPlaceHolder"
                 nzMode="multiple"
                 name="changeAttributes"
                 id ="changeAttributes"
                 nzPlaceHolder="Please select">
    <nz-option *ngFor="let attribute of allAttributes" [nzLabel]="attribute.name" [nzValue]="attribute"></nz-option>
 </nz-select>
 <ng-template #attributeTagPlaceHolder let-selectedList> "and " {{ selectedList.length }} " more items" </ng-template>

where the allAttributes list is formatted like this:

allAttributes= [
{
    "id": 1,
    "name": "Mask"
},
{
    "id": 2,
    "name": "Intensive"
},
{
    "id": 3,
    "name": "Family"
},
{
    "id": 4,
    "name": "Isolation"
}

];

and where the selectedAttributes is one or more of the items in the allAttributes list:

selectedAttributes= [{"id": 1,"name": "Mask"}];

No matter how I create or format the selected attributes list (it can be straight from the allAttributes list), the placeholder cannot be seen and the select is empty, plus when picking all options, the nzMaxTagPlaceholder shows there is an extra item picked.

Can anyone show me the way to set the selected items dynamically?


Solution

  • Try sth like below.

    selectedAttributes = [this.allAttributes[0]];
    

    Since

    {"id": 1,"name": "Hapnikumask"}
    

    is a complex object its equality will be checked by references. So you are defining a new object as selected it will be different from the source object.