Skip to content
Advertisement

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

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.

Advertisement

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

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement