Angular: How to correctly set initial selected objects with @ng-select/ng-select module

Viewed 66

I created a custom component which I call to generate ng-select dropdowns.

However now it occured a problem which I'm not able to fix. When I define initial selected value(s) it shows on the dropdown, but the checkbox stays selectable. This might cause that the object ends up twice in the selected list.

Please see my example on Stackblitz | You'll see that person with id 2 is preselected, but checkbox is unchecked (and that same person can be selected another time, so it is twice in the list)

To create my Component I used the examples from ng-select: example example-source

How do I correctly map the initial selected objects, that the checkbox from selected objects is checked?

1 Answers

The reason is the object set as initial value is new object by comparison it will not be found using _selected.indexOf(item)

If you change your code like below it will work

public selectedPersonList: Array<Person> = [this.personList[1]];

You can do Dynamically like below

replase _selected.indexOf(item) > -1

with

[ngModel]="isSelected(item)"

And defind the isSelect() like below

  isSelected(_item): boolean {
    return  this._selected && this._selected.findIndex(e => e.id == _item.id) > -1;
  }
Related