suraj13k
suraj13k

Reputation: 416

Unable to preselect values in multiple select in angular

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);
})

Upvotes: 2

Views: 66

Answers (1)

Jota.Toledo
Jota.Toledo

Reputation: 28434

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.

Upvotes: 2

Related Questions