A guide to creating a dynamic ngTemplateOutlet in Angular

Below is the HTML code I attempted: 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';

The goal is to display a template based on a variable, for example, room = 'room1', which should then display only the #room1 template.

However, there's an error that says:

Error: templateRef.createEmbeddedView is not a function

Answer №1

To achieve this, you can implement a condition within your ngTemplateOutlet. Here are three different methods you can try:

Approach #1

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

Approach #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];
}

Approach #3 (similar to #2 but with a 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;
}

For further guidance, feel free to explore the Stackblitz Demo provided.

Answer №2

Include the following lines in 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 information, refer to this post

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a dynamic 2x2 grid with centered responsiveness in Angular Ionic framework

I'm having trouble achieving a 2 x 2 grid that is centered on my screen. The code snippet below shows what I have so far in the HTML file. Just to provide some context, this project is meant for a native mobile application. <ion-header> <i ...

navigating a collection of objects and retrieving individual property values

I am having trouble extracting values from an array of objects, specifically only the values from the first object in each sub-array. Here is how my array of objects looks: items [ [ {id: 1, title: "title1", imgUrl: "https://someimage1"}, {id: 2 ...

Customize your webpage's style to reflect your unique identity with user

Is there a way to allow users to customize the style of a webpage? I know I need multiple CSS files, but how can I implement the code that enables this customization based on user preferences? ...

Developing a countdown clock with php and asynchronous javascript (ajax)

Can anyone provide guidance on how to create a real-time database timer? I have a starting time in the database and I am using PHP, looking to incorporate JS or AJAX for optimal functionality. Here is a rough outline of my plan: BEGIN Request server ti ...

Preventing parent click events in AngularJS when clicking on a child element: Tips and tricks

I am facing an issue with a <div> that has a ng-click directive, but this <div> contains a child element also with a ng-click directive. The problem arises when the click event on the child element also triggers the click event of the parent el ...

Iterate through a loop to assign values to an object, then transform it back into an object

My goal is to create a Component with a child that could be any component, so I need to assign the props to this Component. I attempted to do this in a loop because I am unsure about the number of props that should be assigned. //Array of objects that I w ...

React Component for Toggling a Click Event on a Select Tag

I'm currently developing a react app where clicking on a specific text triggers the display of a select tag with several items. However, I've encountered two issues: Upon clicking the text, the select tag appears on ALL list items instead of ju ...

Combining multiple jQuery selector objects into one jQuery object

How can I merge two jQuery selectors into one jQuery object? I attempted to use $("#selector","#selector"), but it didn't work and just returned blank. Are there any built-in methods that can help me accomplish this? Is there a way to do it like thi ...

The Firefox extension is in need of Google Chrome for compatibility

Currently, I am developing a Firefox extension that displays SSL certificate details. My goal is to only view the certificate information without making any alterations. I am attempting to utilize this specific code example, however, the JavaScript code ha ...

What is the best way to implement an Angular Guard that utilizes an API service for validation and redirects in case of failure?

Hello there! I am currently working on an Angular 7 application that deals with time cards. One of the main features I have implemented is a CanActivate Guard for controlling access to certain components. The CanActivate code utilizes Observables to decid ...

Utilizing Typescript to Incorporate Bable's Latest Feature: The 'Pipeline Operator'

Exploring the pipeline operator implementation in my Typescript project has been quite a journey. Leveraging babel as my trusty transpiler and Typescript as the vigilant type checker was the initial plan. The quest began with configuring babel to work sea ...

Determining the value of an object property by referencing another property

Upon running the code below, I encounter the following error message: Uncaught TypeError: Cannot read property 'theTests' of undefined $(document).ready(function() { var Example = {}; Example = { settings: { theTests: $(&apo ...

Looking for an improved, tidier, or more efficient alternative to PHP Random Text?

Is there a more efficient way to generate random text other than using the random_text function in PHP? I'm interested in a method that is quick to render and light on server resources for faster page loading. Should I consider alternatives like Javas ...

Transmitting chosen option using AJAX and JavaScript

I have a select dropdown that I want to use to send a selected option to AJAX and then display it. Here is my HTML: <label>Tag</label> <select id="day"></select> <label>Monat</label> <select id="month"&g ...

Optimal method for displaying content in Vue.js in read-only mode

I am currently working on a code snippet used to display messages exchanged between two users. <template> <main> <form action="" method="post" @submit.prevent="sendMessage"> <textarea name="message" id="messag ...

The extjs datecolumn is displaying dates with a one-day discrepancy

My Ext.grid has a datecolumn, but I'm experiencing an issue where the dates displayed are off by one day. The problem seems to be related to timezones, as when data is added to the store it shows up differently later on. For example, 2013-03-31 becom ...

Display an API generated popup list using Vue's rendering capabilities

I'm attempting to generate a pop-up within a displayed list using custom content retrieved from an API request. Currently, my code looks like this: <template> <div class="biblio__all"> <a v-for="i in items" ...

Tips for accurately dissecting a PDF document to determine the status of checkboxes

Looking for a solution to parse PDF forms on the server side, I have experimented with various node.js modules including pdf2json, hummus, and node-pdftk. While I have successfully retrieved all text fields, I am facing issues when it comes to extracting c ...

Redux state not reflecting changes until second click

My redux store has a simple boolean setup to track whether a sidebar is expanded or not. However, I'm encountering an issue where, even though the default value is false, clicking the toggle button outputs false first. Ideally, if it's initially ...

Incorrect elements displayed by Preact

Currently, I am utilizing Preact (essentially React) to display a list of items stored in a state array. Each item is accompanied by a remove button. My issue arises when the remove button is clicked; the correct item is deleted (I have double-checked this ...