2

Cannot able to preselect values even-though [selectedModels] list are populated with [same objects] from [options] list.

 <select multiple [(ngModel)]="selectedModels" class="col-md-7 form-control">
      <option [ngValue]="obj" [selected]="checkIfSelected(obj)" *ngFor="let obj of options">{{obj.name}}</option>
 </select>

Tried by using [selected] aswell but cannot able to succeed. 'checkIfSelected' method is returning correct boolean values.

Looking for quick help. Thanks!!

After loading selectedModels list from service call, changing the objects from options list

this.selectedModels.forEach(sm => {
      sm = this.options.find(o => o.id == sm.id);
})
4
  • 1
    Can you show how are you populating the selectModels property? Commented Sep 20, 2018 at 19:01
  • Updated my question @Jota.Toledo Commented Sep 20, 2018 at 19:13
  • Ill add an answer in a while, give me some mins Commented Sep 20, 2018 at 19:38
  • Please refer to my answer Commented Sep 20, 2018 at 20:06

1 Answer 1

2

The main issue is the fact that you are trying to set the reference variable inside of the forEach method, which wont have an effect in the array being iterated.

This would be the case if you would set individual members of the reference variable, but that would leave you with 2 different objects, what would inevitably break the select functionality.

The simplest way to solve your issue (keep track of the selected objects + update selected objects when options are loaded) would be to go with an immutable approach by changing:

this.selectedModels.forEach(sm => {
      sm = this.options.find(o => o.id == sm.id);
})

To

const nextSelected = this.options
  .filter(option => this.selectedModels.some(selected => selected.id === option.id)
this.selectedModels = nextSelected;

See this stackblitz for a set of examples showcasing my answer.

Sign up to request clarification or add additional context in comments.

Comments

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.