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

"Alert: Jest has detected that an update to MyComponent in a test was not properly enclosed in an act() function, even though there was no actual update being made. Please

Here's a super straightforward test I've put together: it('renders', () => { const { toJSON } = render( <MockedProvider> <MyComponent /> </MockedProvider> ) expect(toJSON()).toMatc ...

What is the best way to automatically populate additional autocomplete options after selecting certain data, and include new data if it is not already present?

Is it possible to automatically populate the other Autocomplete fields based on matching first and last names? I am encountering scenarios where multiple individuals share similar first or last names but have different addresses. In addition, I would like ...

In Typescript, type errors in Object Spread Syntax are not causing any issues

In the following code snippets, the object spread syntax should generate a typescript error, but surprisingly no errors are being thrown. It's important to note that I intentionally added a typo in the address property for this test. Snippet A.1. - n ...

The JavaScript function on the specified /url page is not functioning properly following the execution of history.push(/url) on click

I have a JavaScript function that toggles the display of login password. However, when I redirect to the login page from another page using history.push(/login), the function does not work. It does work when I use (/login) in the href tag. How can I resolv ...

Accessing Next and Previous Elements Dynamically in TypeScript from a Dictionary or Array

I am new to Angular and currently working on an Angular 5 application. I have a task that involves retrieving the next or previous item from a dictionary (model) for navigation purposes. After researching several articles, I have devised the following solu ...

Tips on effectively rendering child components conditionally in React

My components currently consist of an AddBookPanel containing the AddBookForm. I am looking to implement a feature where the form is displayed upon clicking the 'AddBookButton', and hidden when the 'x' button (image within AddBookForm c ...

A guide on refreshing the dependencies list within Angular's node modules and package.json files

A close friend sent me the angular src folder, which I used to create a new Angular project. However, when I replaced my newly created src folder with my friend's and tried running the application using npm start, I encountered errors related to missi ...

Having difficulty showing the successful JSON output in either the view or an alert

In my CodeIgniter project, I have three input fields named name, emp_id, and crm_id. I enter the id value and send it to the controller via AJAX and JSON to retrieve all information related to that id. The issue is that while I can see the correct output i ...

Tips for sorting through JSON Data to isolate a particular day

I developed a Food-App that displays a different menu every day. I retrieve the local JSON Data using Axios and attempt to filter the mapped menu with .filter. My issue lies in not being able to filter specific days. I attempted to restructure the JSON Da ...

What are the reasons to steer clear of setting y.innerHTML equal to x.innerHTML?

If we have a DIV x on the webpage and want to duplicate its contents into another DIV y, we might be tempted to use the following code: y.innerHTML = x.innerHTML; This can also be achieved using jQuery: $(y).html( $(x).html() ); However, it is recommen ...

Replacing jQuery.ajax from a different directory/domain - problem with using relative URLs

We are incorporating scripts from various sources and domains, including one that contains the definition for jQuery.ajax function. Calls to jQuery.ajax are being made from different places and domains using relative URLs, such as jQuery.ajax("my/relativ ...

What is the name of the scrolling header effect achieved in the following?

I've been seeing a lot of people using a unique header effect lately and I'm curious to learn more about how it's done. Can anyone explain the process behind achieving this effect, what it's called, and if there are any good tutorials a ...

Creating a personalized context menu in Javascript: The ultimate guide to incorporating copy and paste features

We are developing a unique context menu for our online text editor, complete with copy/paste options. However, we encountered difficulties accessing the system clipboard from within the browser. It once seemed impossible to achieve this, as discussed in th ...

React-native horizontal sliding plugin

Can anyone recommend a reliable horizontal slider plugin for react-native? I've come across some options, but they haven't been working as smoothly as I'd hoped. ...

How to implement a for loop within a Vue.js method

Within Vuejs, I have a method that updates multiple variables based on user selection. methods: { updateChart(){ this.chart1.series[1].data = [this.$store.state.selectedcities[0].value[1]]; this.chart1.series[2].data = [this.$store.state.selecte ...

What should be transmitted to the front-end following the successful validation of a token on the server?

My process starts with a login page and then moves to the profile page. When it comes to handling the token on the backend, I use the following code: app.use(verifyToken); function verifyToken(req, res, next) { if (req.path === '/auth/google&ap ...

Discover the power of AngularJS's ng-route feature for creating a dynamic and seamless one-page HTML template experience

I'm attempting to create a dynamic header using ng-repeat. Here's the initial code: <ul class="right"> <li><a href="#carousel">Home</a></li> <li><a href="#about-us">About Us</a></li> &l ...

Mastering the art of grouping by a key and generating sub-objects from a plain array of key-value pairs in JavaScript ES5 without relying on third-party libraries

My dataset consists of an array of objects, each containing 4 keys: [ { "team": "USA", "team_profile_id": "10", "player": "Captain America", "player_id": "10X1" }, { "team": "USA", "team_profile_id": "10", "player": "The ...

NodeJS Express Application Error: Unable to access /url

I've been troubleshooting this issue for an hour now and I'm stumped. I can't seem to access the specified URL. I created a NodeJs Express app, but when I try to access http://localhost:3000/users/login, I receive the error message Cannot GE ...

What's the best way to insert values into data binding within a Typescript/ Angular mat Table?

Objective: Create a dynamic table using JSON data <mat-table class="mat-elevation-z8" *ngIf="carrierRates" [dataSource]="carrierRates"> <ng-container *ngFor="let columnName of columnsList" matColumn ...