1

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

2 Answers2

1

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

KShewengger
  • 7,853
  • 3
  • 24
  • 36
  • Although the solution works, you don't need the `selectedRoom()` method. Setting `` is enough. And of course `strict` needs to be set to `false` in `tsconfig.json`, otherwise Angular will complain about a million things. – dreamLo Jan 28 '22 at 13:56
0

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

Kirubel
  • 1,461
  • 1
  • 14
  • 33