4

I am trying to pass #tmp in the mat-select with template-outlet and I' am not able to display the select options. Below here is my code and a link to stackblitz

    <mat-form-field>
        <mat-select 
           [ngModel]="selectedFoods" 
           (ngModelChane)="selectedFoods" placeholder="Favorite food" multiple>
        <ng-container *ngFor="let food of allfoods"
            [ngTemplateOutlet]="tmp"
            [ngTemplateOutletContext]="{ $implicit: food}">
        </ng-container>
        </mat-select>
    </mat-form-field>
    <ng-template #tmp let-food>
      <mat-option [value]="food.value">
        {{food.viewValue}}
      </mat-option>
    </ng-template>

https://stackblitz.com/edit/angular-mat-select-with-ngmodel-mujorn?embed=1&file=app/select-overview-example.ts

anonymous
  • 1,499
  • 2
  • 18
  • 39

1 Answers1

5

This seems to work.I think the important part is still having the <mat-options> inside the <mat-select> and not as part of the template.

https://stackblitz.com/edit/mat-select-with-ngtemplateoutlet-example?devtoolsheight=33&file=app/select-overview-example.html

<mat-form-field>
    <mat-select>
       <mat-option *ngFor="let food of allfoods"  [value]="food.value">
          <ng-container [ngTemplateOutlet]="tmp" [ngTemplateOutletContext]="{food: food}">
          </ng-container>
       </mat-option>    
    </mat-select>
</mat-form-field>

<ng-template #tmp let-food="food">
    {{food.viewValue}} <b> From Tmp</b>
</ng-template>


Dropdown showing template value in select

Stephen Cooper
  • 1,069
  • 7
  • 15
  • This is fine but how do I pass the value along with the template, {{food.viewValue}} – anonymous Feb 26 '21 at 07:46
  • Yes, I have added this to the answer above now. It was present in the Stackblitz. – Stephen Cooper Feb 28 '21 at 14:32
  • No, i mean i wanted to add like, {{food.viewValue}} From Tmp – anonymous Feb 28 '21 at 14:37
  • I want to add value through the ng-template – anonymous Feb 28 '21 at 14:39
  • [value] represents an input property on mat-option but that does not exist on ng-template which is why you cannot write that code. – Stephen Cooper Mar 08 '21 at 20:58
  • Yes for this, I pass the food object in the value property and get the whole object back through output property – anonymous Mar 09 '21 at 17:16
  • Is possible to do this but having the ng-template in a parent component ? As the #tmp is not known in the parent, I'm not so sure how to do it. I answer here as it's quite similar to what I want to achieve but splitting the ng-template in another component. – Javier May 03 '21 at 10:08
  • 1
    @Javier you can definitely do this and I have written an article that demonstrates passing a template in from a parent just as describe. https://indepth.dev/posts/1405/ngtemplateoutlet – Stephen Cooper May 04 '21 at 19:45