Search code examples
angulartypescriptangular-materialangular7angular2-forms

Angular preSelected options in custom component not showing


I am trying to make a component that has a multi select dropdown. when I create an instance of this component i want to pass it a list of objects (in my case ICatagory) to show as the options. I also want to pass it a list of that same object(in my case ICatagory) as the preselected values.

So far I can pass it the list of objects and it will show it as the options, I am also able to pass it the preSelected values I want. however even though I can pass the preSelected, it does not show these values as selected.

https://stackblitz.com/edit/angular-aryu5y

This is the stackblitz i made to clarify. NOTE: when it loads there is nothing selected. I want the preSelected values to be selected on creation.

still somewhat new to Angular so forgive any anti convention patterns you see.


Solution

  • All, I was able to figure it out.

    there is something called [compareWith] that goes in your

    https://stackblitz.com/edit/angular-qpzg9s

    ^^^stack blitz with solution.^^^

    code diffrence. in my-drop-down.html i added :

     [compareWith]="byId" 
    

    into the mat-select

    in my-drop-down.ts i added :

    byId(obj1,obj2){
     if(obj1 != undefined && obj2 != undefined){
        return obj1.id === obj2.id;
      }
    }
    

    this was able to preSelect the options as objects.

    if anyone has a better answer im open ears.