Guide on how to showcase the template by leveraging the roomList information with 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>

Is there a way to dynamically display the template based on the value of the roomList object? For example, if the name is 'Room2', then Room2 template will be displayed in the ngTemplateOutlet.

Answer №1

To implement this functionality, make sure to define a TemplateRef and reference it 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>

Check out the DEMO here

Answer №2

give this a shot

<div class="Layout-body">
  <ng-container *ngFor="let dt of roomList; index as i" [ngTemplateOutlet]="([RoomA, RoomB])[i]" [ngTemplateOutletContext]="{ data: dt, i: i }" >
    </ng-container>
</div>

<ng-template #RoomA let-data="data" let-i="index">
    {{data | json}}
  </ng-template>
<ng-template #RoomB let-data="data" let-i="index">
  {{data | json}}
</ng-template>

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

The value of additionalUserInfo.isNewUser in Firebase is consistently false

In my application using Ionic 4 with Firebase/AngularFire2, I authenticate users with the signinwithemeailandpassword() method. I need to verify if it's the first time a user is logging in after registering. Firebase provides the option to check this ...

Show a particular set of data in the template

My Angular application consists of a sender and a receiver component that are linked through the data service. The sender template includes an input field where users can enter a number, which is then transmitted to the receiver when a button is clicked. T ...

PHP code to display "ed elements that do not adjust height"

A php script is being utilized to scan a directory and populate a gallery with all the images. Within the <div id="content"> tag, the function <?php create_gallery("path"); ?> loads all the images. The issue arises when the height of the <d ...

Dealing with CORS policy challenge

I am encountering an issue with Access to XMLHttpRequest at 'http://demo.equalinfotech.com/Iadiva/images/product/1634623781ladiva_barbara_01.glb' from origin 'http://localhost:8100' being blocked by CORS policy due to the absence of the ...

Adding specific props, such as fullWidth, at a certain width, like 'sm', in Material UI React

My goal is to include the fullWidth prop when the screen reaches a size of 600px or greater, which is equivalent to the breakpoint sm. I attempted to implement the following code, but unfortunately, it does not seem to be functioning as intended. [theme ...

Using Plotly.js to generate a visually stunning stacked and grouped bar chart

Is there a way to generate a bar chart on Plotly.js that features both grouped and stacked bars? Ideally, I am looking for a structure similar to the one shown here: Barchart with stacked and grouped charts ...

Is it possible to derive a TypeScript interface from a Mongoose schema without including the 'Document' type?

Using ts-mongoose allows me to define interfaces and schemas for my data in one place. I then export them as a mongoose schema along with the actual interface. The challenge I'm facing is finding a simple way to extract that interface without includi ...

Managing image downloads from a Node.js server: Tips and Best Practices

Currently, I am in the process of learning node.js and recently encountered a scenario where I need to download an image from the server by clicking a button on the webpage. I have set up an endpoint that receives two parameters: - The name of the image ...

Top method for changing Enum to Set in TypeScript

Take a look at the enum below: enum Animes { OnePiece = 'One Piece', Naruto = 'Naruto', Bleach = 'Bleach' } How can we efficiently transform this enum into a Set? ...

"Exploring Angular 9: A guide to retrieving form data with an array of objects [Revised as of July 29th, 2020

I am encountering an issue with my Angular 9 form code. I am getting the error "ERROR TypeError: Cannot read property 'mobile_number' of undefined" and I need help in resolving this problem. <form (ngSubmit)="processForm()"> & ...

Issue with displaying tab icons in Ionic 4

After updating the versions of Angular, Cordova, and Ionic, I started experiencing an issue with the tab icons displaying partially. Specifically, when my app loads with 4 tabs, only the first and third icons are visible. However, upon touching one of the ...

"jQuery Hide-and-Seek: A Fun Way to Manip

I am facing a challenge with a set of divs that I need to dynamically show and hide based on user interactions with questions. Essentially, the user will be presented with a question. Based on their answer, specific content with a title and description wi ...

Show dynamic outcomes on the site

I'm currently in the process of building a website for a travel search engine and I'm interested in displaying the results in a similar manner to what is done on Hipmunk. Here are some key details: The website is being developed using Django. ...

Oops! Make sure to call google.charts.load before calling google.charts.setOnLoadCallback to avoid this error

My HTML file includes the following imports: <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> ...

The Angular2 Observable fails to be activated by the async pipe

Take a look at this simple code snippet using angular2/rxjs/typescript public rooms: Observable<Room[]>; constructor ( ... ) { this.rooms = this.inspectShipSubject .do(() => console.log('foo')) .switchMap(shi ...

How to Use Framer Motion in Next.js for window.innerWidth Less Than 768

I am trying to use window.innerWidth to control the timing of an animation (Framer Motion) in my Next.js project, but I keep encountering the error message: ReferenceError: window is not defined Here's a simplified version of my ValuesSection.jsx co ...

Looking to adjust the background-image size of a table cell (td) upon clicking a specific

I have a website where I would like to display logos of different games with links attached to them. I have managed to adjust the size of the image on hover, but now I am looking for a way to keep the size bigger after clicking on the link. Is there a simp ...

What could be causing the error message "Error: Cannot modify headers after they are sent" to appear?

I am attempting to insert data into an MS SQL server when a JSON Data API POST request is made. var express = require('express'); var app = express(); var sql = require('mssql'); // Connection string parameters. var sqlConfig = { u ...

Troubleshooting Database Saving Problem with Vue.js and Ruby on Rails

Trying to configure a nested form with Vue.js in a Rails application to save ingredients for a recipe. While all other details of the ingredients are saving correctly, the ingredient name (from an input field) is not getting saved in the database. How can ...

Experiencing the issue with the $.getJSON function bug

Is there a way to ensure that my code processes the $.getJSON function fully? I am encountering an issue where only the first alert, 'inside1', is triggered when running the site. The second alert, 'inside x2', never gets processed. Any ...