user13780186
user13780186

Reputation:

How to make the ngTemplateOutlet dynamic in angular

here's the code that I tried: HTML

<ng-container [ngTemplateOutlet]="room"></ng-container>

<ng-template #room1>
   test 1
</ng-template>

<ng-template #room2>
    test 2
</ng-template>

<ng-template #room3>
     test 3
</ng-template>

TS

room = 'room1';

What I'm trying to do is to display the template based on the variable for example. room = 'room1' then it will display only the template #room1.

But I'm getting an error which is this one: Error: templateRef.createEmbeddedView is not a function

Upvotes: 1

Views: 3769

Answers (2)

KShewengger
KShewengger

Reputation: 8269

You can do by putting a condition in your ngTemplateOutlet. You can try either of these 3 methods below:

Method #1

<ng-container [ngTemplateOutlet]="room === 'room1' ? room1 : room === 'room2' ? room2 : room3"></ng-container>

Method #2:

HTML

<ng-container [ngTemplateOutlet]="selectedRoom"></ng-container>

Component

@ViewChild('room1') room1: TemplateRef<any>;
@ViewChild('room2') room2: TemplateRef<any>;
@ViewChild('room3') room3: TemplateRef<any>;

room = 'room1';

get selectedRoom() {
  const rooms = {
    room1: this.room1,
    room2: this.room2,
    room3: this.room3
  } 

  return rooms[this.room];
}

Method #3 (the same as #2 but using conditional approach):

HTML

<ng-container [ngTemplateOutlet]="selectedRoom"></ng-container>

Component

...

get selectedRoom() {
  return this.room === 'room1'
    ? this.room1
    : this.room === 'room2'
    ? this.room2
    : this.room3;
}

Attached herewith is a Stackblitz Demo for your reference

Upvotes: 2

Kirubel
Kirubel

Reputation: 1627

Add these to your component.ts file

@ViewChild('room1', { static: false }) room1:TemplateRef<any>;
  @ViewChild('room2', { static: false }) room2:TemplateRef<any>;
  @ViewChild('room3', { static: false }) room3:TemplateRef<any>;

For more details check this answer

Upvotes: 0

Related Questions