Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material Multiple Select Options with Object

Current Setup :

  • Angular 4
  • Angular Material
  • Firebase (Firestore)

Expected Behavior :

  • Initially selecting multiple objects from my array inside my angular material multiple select.

Current Behavior :

  • No item is initially selected.
  • They get properly selected when clicking them.
  • Saving them in Firebase(Firestore) work (Saving the document reference)

Additional Note(s) :

  • If I use only an object property they do get initially selected properly.
  • classe.multiclassement is an array of reference
  • classes is my array of objects

Code Sample :

<mat-select placeholder="Multiclassement" [(ngModel)]="classe.multiclassement" multiple>
  <mat-option *ngFor="let c of classes | async" [value]="c">{{c.nom}}</mat-option>
</mat-select>
like image 593
DominikG Avatar asked Nov 12 '17 04:11

DominikG


1 Answers

Since we are dealing with objects, the objects in your multiclassesment array have no reference to the objects in your classes array, so therefore Angular cannot make the binding. We can solve this by using compareWith (docs) like so:

<mat-select [compareWith]="compareWithFn" placeholder="Multiclassement" 
            [(ngModel)]="classe.multiclassement" multiple>

and TS:

compareWithFn(item1, item2) {
  return item1 && item2 ? item1.nom === item2.nom : item1 === item2;
}

DEMO

like image 151
AT82 Avatar answered Oct 23 '22 08:10

AT82