Utilize dynamic components to load varying data sets multiple times

Is there a way to dynamically load a component multiple times and pass data based on certain values so that it will display with real-time information?

I came across an example at the following link:

In this example, there is a messageComponent with a "message" property. We add a template in the hostComponent's HTML file like this:

<div style="text-align:center">
     <h1>
         Welcome to {{ title }}!
     </h1>
     <template #messagecontainer>
     </template>
 </div>

Instead of the template tag, the messageComponent will be inserted.

I am looking for a solution where we can iterate this template multiple times and dynamically pass different values for the "message" property in the messageComponent.

Answer №1

Below outlines my method:

  • Start by setting up a container in your template to hold all messages
<ng-container #messageContainer></ng-container>
  • Create a function that can generate a component and place it in the view
private createComponent (compClass) {
   const compFactory = this.cfr.resolveComponentFactory(compClass);

   return this.messageContainer.createComponent(compFactory);;
 }
  • Load the component multiple times based on incoming data, keeping track of which components have been loaded so they can be destroyed when necessary for loading another dynamic component.
 private loadNewComponentList () {
   this.messages.forEach((msg, idx) => {
     this.destroyCompFromList(this.componentList[idx]);

     const comp = this.createComponent(componentMap[this._crtComp]);

     (comp.instance as any).message = msg;

     comp.changeDetectorRef.detectChanges();

     this.componentList[idx] = comp;
   });
 }

Take a look at this StackBlitz demo.

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

Dealing with GraphQL mutation errors without relying on the Apollo onError() function

When managing access to an API call server-side, I am throwing a 403 Forbidden error. While trying to catch the GraphQL error for a mutation, I experimented with various methods. (Method #1 successfully catches errors for useQuery()) const [m, { error }] ...

Strange error message regarding ES6 promises that is difficult to interpret

Snippet getToken(authCode: string): Promise<Token> { return fetch(tokenUrl, { method: "POST" }).then(res => res.json()).then(json => { if (json["error"]) { return Promise.reject(json); } return new Token ...

Encountering an unexpected token error while trying to compile a Typescript file to Javascript, even though it had previously worked

In my Typescript project, I usually run it using "ts-node". $ ts-node .\src\index.ts it works =) However, I wanted to compile it to Javascript, so I tried the following: $ tsc $ node .\src\index.js Unfortunately, I encountered the f ...

Display Google font as SVG path but encapsulate within a promise

I'm facing an issue with the following script, where it performs an async operation. My goal is to wrap it in a promise, but I'm unsure about the right approach. static convertGoogleFontToSVG(): Promise<string> { const url = 'htt ...

What is the method for including a TabIndex property in a JSON file?

https://i.sstatic.net/ISi72.png I discussed the integration of HTML fields within a JSON file and highlighted how to utilize the TabIndex property effectively in JSON files. ...

Exploring Angular5 Navigation through Routing

I have been working with Angular routing and I believe that I may not be using it correctly. While it is functional, it seems to be causing issues with the HTML navbars - specifically the Info and Skills tabs. When clicking on Skills, a component popup s ...

Transform **kerry James O'keeffe-martin** into **Kerry James O'Keeffe-Martin** using TypeScript and Java Script

Is there a way to capitalize names in both TypeScript and JavaScript? For example, changing kerry James O'keeffe-martin to Kerry James O'Keeffe-Martin. ...

Guide on utilizing the maven-exec-plugin to execute npm clean commands

I am currently utilizing the exec-maven-plugin in my project. I have added extensions for npm install and npm clean commands. Below is the configuration section of the plugin in the pom file, which includes extensions for npm install, tsc run, and npm clea ...

Firebase Function deployment encountered an issue during the build phase, despite the predeploy process

My react.js project includes Firebase functions that are configured in a sub-folder called root/functions. These functions are written in typescript and have paths option set in tsconfig.json. In my functions/index.ts file, I import files from various loca ...

Navigating to the tsconfig.json file based on the location of the file being linted

In my monorepo, each package currently contains a .eslintrc.cjs file with the following setup: Package-specific ESLint Configuration const path = require('path') const ts = require('typescript') const OFF = 0 const WARN = 1 const ERROR ...

Unleashing the Potential of a Single Node Express Server: Hosting Dual Angular Apps with Distinct Path

I have successfully managed to host two separate angular applications (one for customers and one for company staff) on the same node server, under different paths. The setup looks like this: // Serve admin app app.use(express.static(path.resolve(__dirname, ...

Exploring the narrowing capabilities of TypeScript within while loops

When I write while loops, there are times when I know for sure that a certain value exists (connection in this case), but the control flow analysis is unable to narrow it down. Here's an illustration: removeVertex(vertex: string) { const c ...

Error: Trying to modify an immutable property 'title' of object '#<Object>' - React JS and Typescript

Whenever I press the Add button, all input values are stored in a reducer. However, if I append any character to the existing value in the input fields, it triggers the following error: Cannot assign to read only property 'title' of object &apos ...

Angular 17 | Angular Material 17.3.1: Problem encountered with Angular Material form field focus and blur event handling

I attempted to apply (blur) and (focus) effects to my mat-form-field input field, but it seems like they are not working properly on my system. Here is a code snippet that resembles what I am using: html file <form class="example-form"> ...

Can the data cells of columns be dynamically adjusted to align them on a single vertical line?

For some time now, I have been grappling with a CSS issue. I am working with a table that has 3 columns displaying departures, times, and situational text for scenarios like delays or cancellations. However, as evident from the images, the alignment of th ...

Is there a way to customize the Color Palette in Material UI using Typescript?

As a newcomer to react and typescript, I am exploring ways to expand the color palette within a global theme. Within my themeContainer.tsx file, import { ThemeOptions } from '@material-ui/core/styles/createMuiTheme'; declare module '@mate ...

Issue with the scoring algorithm using Angular and Spring Boot

Hello, I have created a scoring algorithm to calculate scores, but I encountered an error in "salaireNet". ERROR TypeError: Cannot read properties of null (reading 'salaireNet') at ScoringComponent.calculateScore (scoring.component.ts:33:55) ...

"Exploring Angular: A guide to scrolling to the bottom of a page with

I am trying to implement a scroll function that goes all the way to the bottom of a specific section within a div. I have attempted using scrollIntoView, but it only scrolls halfway down the page instead of to the designated section. .ts file @ViewChild(" ...

Using Angular2, assign a value to the session and retrieve a value from the session

I am having trouble getting and setting a session. Here is my code: login_btnClick() { var NTLoginID = ((document.getElementById("NTLoginID") as HTMLInputElement).value); this._homeService.get(Global.BASE_USER_ENDPOINT + '/EmployeeDe ...

Strict type inference for the number data type in TypeScript

I am interested in inferring the number type within this function: type Options = { count: number }; function bar<C extends Options>(options: C): C['count'] extends 3 ? 'x' : 'y' {} bar({ count: 3 }) // x bar({ count: ...