How to display the template based on the roomList data using ngTemplateOutlet in angular

Tags: , ,



TS

roomList = [{
 name: 'Room2'
}]

HTML <

div class="Layout-body">
      <ng-container *ngFor="let dt of roomList; index as i" [ngTemplateOutlet]="Room1" [ngTemplateOutletContext]="{ data: dt, i: i }" >
        </ng-container>
    </div>
    
    <ng-template #Room1 let-data="data" let-i="index">
        {{data}}
      </ng-template>
    <ng-template #Room2 let-data="data" let-i="index">
      {{data}}
    </ng-template>

How to display room template based on the roomList name.

for example ‘Room2’ then in ngTemplateOutlet will display the template of Room2.

Answer

You need to create TemplateRef and refer that in the html using this

import {
  Component,
  VERSION,
  ViewChild,
  TemplateRef
} from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  roomList = [{
      name: "Room2"
    },
    {
      name: "Room1"
    }
  ];

  @ViewChild("Room1") Room1: TemplateRef <any> ;
  @ViewChild("Room2") Room2: TemplateRef <any> ;
}
<div class="Layout-body">
  <ng-container *ngFor="let dt of roomList; index as i" [ngTemplateOutlet]="this[dt.name]" [ngTemplateOutletContext]="{ data: dt, i: i }">
  </ng-container>
</div>

<ng-template #Room1 let-data="data" let-i="index">
  {{data.name}}
</ng-template>
<ng-template #Room2 let-data="data" let-i="index">
  {{data.name}}
</ng-template>

DEMO



Source: stackoverflow