1

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 Answer 1

2

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;
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Makes totally sense, thanks. Is there a more dynamic way to do this? The selectedPersonList is returned from server, so it might be empty or having mutliple preselected objects.
Check the edit now for dynamic way, instead of check use the predicate function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.