Using the ng-template-outlet within two separate loops

I am facing an issue where I need to repeat the same code in two different places. The profiles, profile1 and profile2 are arrays. I want to display the same HTML code without duplicating it.

profile1 = [{name : 'mr.A1',age : 25 },
{name : 'mr.B1',age : 23}];
profile2 = [{name : 'mr.A2',age : 25 },
{name : 'mr.B2',age : 23}];

<ng-container *ngFor="let x of profile1">
<ng-template #templateRef>
<p> {{x.name}}</p>
<p> {{x.age}}</p>
</ng-template>
<ng-template [ngTemplateOutlet]="templateRef"></ng-template>
</ng-container>

// The above code displays the following result
mr.A1
25
mr.B1
23

// The below code currently does not show anything

<ng-container *ngFor="let x of profile2">
<ng-template [ngTemplateOutlet]="templateRef"></ng-template>
</ng-container>

// My goal is to achieve the following results using ngTemplateOutlet
mr.A2
25
mr.B2
23

Answer №1

For personalized components, this type of dynamic behavior works best.

If you opt for this approach, keep in mind that you will need to utilize ngTemplateOutletContext to pass data to your template references.

Here is how it can be implemented:

<ng-template #profile let-person>
  <div>
    {{ person?.name }} is {{ person?.age }} years old.
  </div>
</ng-template>

<h1>First batch</h1>

<ng-container *ngFor="let person of profiles">
  <ng-container *ngTemplateOutlet="profile; context: { $implicit: person }"></ng-container>
</ng-container>

<h1>Second batch</h1>

<ng-container *ngFor="let person of profiles">
  <ng-container *ngTemplateOutlet="profile; context: { $implicit: person }"></ng-container>
</ng-container>

Check out the Stackblitz example here - Read more in the official documentation

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

What is the best way to iterate over objects within an array in Ionic version 3?

In my array of objects, each object contains another object. I was able to retrieve the value of the supplier's name using the following loop, but it only retrieves the value from one object. I am looking for a way to obtain the supplier's name f ...

Discrepancies observed between Protractor local and global installations

I've been tackling a tough issue with two other developers for almost 24 hours now. We have a conf.js file that runs smoothly when invoked in Terminal with the command protractor conf.js using the globally installed version of Protractor. Each test pa ...

Struggling to update the previousCode state with the useState hook in React

I'm having trouble understanding why the state isn't changing when using setPreviousCode in React and JavaScript. I'm trying to store the previously scanned text in the variable previousCode. import React, { useEffect, useState } from " ...

Strangely behaving data binding when using socket.io

Recently, I've been experiencing some strange behavior while developing a socket.io app with Angular 2 on the frontend. This unusual issue seems to be related to the interaction between Angular 2 and socket.io, as I have never encountered anything lik ...

The scroll depth provided by the overflow:scroll; property is insufficient

When using the CSS overflow:scroll; property, I noticed that there is a limitation on the scrolling depth. It seems that the scrollbar doesn't scroll far enough to reveal all the hidden data. If you are interested in checking out the code on my Githu ...

Creating a dynamic navigation menu in Angularjs using UI-Bootstrap tabs and UI-Router for seamless user

When working on this Plunker, I encountered an issue with the functionality of menu links and tabs. The problem arises when trying to navigate between 'Route 1' and 'Route 2'. Clicking twice on 'Route 1' doesn't properly ...

Is there a way to ensure that the navigation bar only appears at the top of the page?

Is there a way to only show the navigation bar when a user scrolls to the very top of the page? Currently, the nav bar appears whenever the user scrolls up, regardless of the screen position. Html <header class="nav-down"> <div> navigation ...

transform an array to an array consisting of objects

Below is an array list that needs to be converted into a specific form. var data = [ "USA", "Denmark", "London"]; The desired format for the array is: var data = [ { "id" : 1, "label": "USA" }, { "id" : 2, "label": "Denmark" }, { "id" : 3, "label": " ...

The most effective way to initiate an action following a popup

Here's a button that triggers the opening of a popup: <button type="button" id="btnBuscarCuenta" onClick="javascript:AbrirPopUpBusqueda('id_AyudaCuentas', 'pop_cuentas_contables.cfm','', '900px&a ...

The list countdown for loop only appears in the initial iteration

Hey there, I'm currently facing an issue with duplicating my JavaScript countdowns and displaying images of cards on each loop iteration. Strangely, the countdown only appears in the first instance even though it's within the loop. I'm seeki ...

Attempting to authenticate user with Node.js and MongoDB integration

I have been attempting to log in a user, but I keep encountering the error "user is not defined". I've made sure to use both upper and lowercase variations of "user/User", yet it continues to show up as undefined. var mongoose = require("mongoose") va ...

Turn off the feature that prohibits the use of variables before they are

I'm struggling to disable this setting in my tsconfig file. The TS documentation doesn't seem to have any information about how to do it. no-use-before-declare I'm facing an issue where my test stub data objects are interfering with each ot ...

Having trouble with @HostListener on iPad or iOS devices? I'm currently using a Bluetooth keyboard to navigate and interact with an Angular app

I am currently creating a web application using Angular 6 for an iPad with a screen size of 9.7 inches. I have implemented code similar to the one found at this link. import { Component, HostListener } from '@angular/core'; export enum KEY_CODE ...

Tips for creating horizontal dividers with CSS in Vuetify using <v-divider> and <v-divider/> styling

Currently, I am working on a project using Vue.js and adding Vuetify. However, I need to use a component. .horizontal{ border-color: #F4F4F4 !important; border-width: 2px ; } <v-divider horizontal class=" horizontal ...

One efficient way to handle multiple concurrent tasks in NodeJs is by using the forEach method to iterate

Having trouble getting the promises to return any values, as they are coming back empty. Despite following suggestions on Stack Overflow, I am still unable to resolve this issue. Frustration levels are high and I'm feeling lost; Can anyone help me pi ...

Sorting an array of objects in Typescript using a dynamic property name for generics

My goal is to develop a versatile, typed function that can arrange an array of objects by a numerical value housed under a dynamically named property within each object. Here is my current progress: export const sortByNumber = <T, K extends keyof T> ...

Arrange an array of strings in which the elements follow the format "Name:Score"

I am currently working with a string array that is stored in LocalStorage. Within this array, each element follows the format "Name:Score". My goal is to sort this array by score in order to create a leaderboard. How can I efficiently achieve this? Perhap ...

Is the function failing to detect the updated variable because it is not declared as a global variable?

I have created a quiz with 7 select boxes and a submit button, aiming to display a warning error if the select boxes are not changed or show the score if they are changed. I initialized a variable called 'changed' as false. When a select box is ...

Utilizing Chained Conditions in React JSX

Although the code below is functional and yields the desired outcomes, I can't help but question if there's a better way to do it. { Conditon1?<ChildComponent />:Condition2?<p>Hi</p>:<p>Bye</p> } I'm partic ...

Guide to displaying a loading message while performing a synchronous AJAX request in a web browser

Is there a way to display a waiting message during a synchronous AJAX call in the browser? I attempted to use the code below, but even after turning off the web server, the "Saving" message did not appear. After some time, only an error event from the AJA ...