Using a loop to pass a template to a function and create a dynamic component

I am currently attempting to dynamically generate a component while looping through a list. However, I have encountered an issue where the template cannot be passed to the function for creating the component. The error message indicates that the viewContainer is undefined.

Error: Cannot read property 'createComponent' of undefined

export class DataEditModalComponent {
  public fields = [
    { component: ComponentA },
    { component: ComponentB }
  ]

  public constructor(private readonly componentFactoryResolver: ComponentFactoryResolver) { }

  public createComponent(component: any, viewContainer: ViewContainerRef) {
    const factory = this.componentFactoryResolver.resolveComponentFactory(component);
    viewContainer.createComponent(factory);
  }
}
<div *ngFor="let field of fields">
  <ng-template #template *ngIf="field.component && createComponent(field.component, template)">
  </ng-template>
</div>

Answer №1

Here is an illustration of how this concept could be put into action:

Module:

export const modules = [
  { module: ModuleA },
  { module: ModuleB }
]

loadedModules = [];

onInit(): void {
  this.loadedModules = modules.filter(item => item.module).map(item => item.module)
}

Structure:

<ng-container *ngFor="let m of loadedModules" [ngComponentOutlet]="m"></ng-container>

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

Can you please provide instructions on how to expand the view in the title bar for a JavaScript/CSS/HTML UPW project?

Struggling to integrate the title bar in a UWP project using JavaScript/CSS/HTML and having trouble accessing the necessary APIs. Came across a custom helper class written in c++ in UWP samples on Github, but unable to reference it in my javascript code. H ...

Embedding a pop-up window in PHP script

My current task involves creating a table where clicking on an ID opens a popup window with a menu for changing row values and adding comments. However, I am facing difficulty in generating a link for each row: foreach ($results as $row) { // Each $row is ...

Utilizing PHP Variables in Jquery Ajax Success Response

I have a webpage that displays a list of routes. When a user clicks on a route, an AJAX request is sent to save the selected route in the database. On the same page, in a different tab, I am running a query to fetch related information about the selected ...

Instructions for extracting the href value from an anchor tag using JavaScript within a specified string

How can I retrieve the href value of the last anchor tag in the provided content string using pure JavaScript, excluding jQuery? var contents = '<div id="content"><a href="http://www.okhype.com/wp-content/uploads/2016/12/ruffcoin-made-in-aba ...

Unlocking the power of tailwind colors in javascript

I want to style my ApexCharts using my tailwind colors like red-500, but I cannot use CSS classes or the theme() function in a post-CSS context. Since I have already extended the default config, I cannot reference it either. One potential solution could ...

Passing ngModel from controller to directive in AngularJS

I'm currently working on a project that involves a controller with an attribute directive nested inside of it. This directive requires access to the ngModel of its parent controller. For more context, feel free to check out this Plunkr. Issue at Han ...

Display data in Angular2 before loading from the http source

Having a challenge with asynchronous data loading from the server. The view isn't displaying any data because rendering happens before the data is loaded. Here is the code snippet provided: user: User = new User() ngOnInit() { this.userS ...

How can I modify the fill color of a Cell when hovering over a Bar Chart in Recharts?

I have been rendering the chart in the following manner: <BarChart width={868} height={40} data={data} margin={{top:0, bottom: 10, left:0, right:0}} barSize={5}> <Tooltip labelStyle={{ textAlign: &apo ...

In ReactJS, organizing arrays within arrays for nesting purposes

Recently, I initiated a fresh project with React. I designed and brought in images by importing them: import Tip1 from "./img/Tips1.png"; import Tip2 from "./img/Tips2.png"; import Tip22 from "./img/Tips2-2.png"; ...

Error message while running jQuery 3.2.1: issues with UL and LI

I have a link that displays the desired outcome Despite using jquery version 3.2.1, when I insert my code into Dreamweaver cc 2018, it fails to work. On my jsfiddle, the selection is sorted alphabetically, but on my web page it is not. var mylist = $( ...

Fixing JavaScript Image Swap Bugs

Seeking assistance with a JavaScript Image Swap creation. Can anyone provide guidance on identifying coding errors in my JavaScript? Any help or pointers on correct usage of getElementById would be greatly appreciated! <title>Photo Gallery</tit ...

Creating unique image control buttons for each image within a div using a combination of CSS and JavaScript

How can I create image control buttons, such as close, resize, and rotate, for each individual image when hovering over it? Each image is contained within a draggable div. I want to display an image control button next to each image. This button should on ...

Is it possible for a jQuery selector to retain its object? What can be done to prevent it

One interesting scenario involves a dropdown element within a container. <div class='container' /> <script> var dropdown = "<select class='multi-dropdown'> ... </select>" </script> Every time the value ...

Guide on darkening the surrounding div of an alert to give it a modal-like effect

I want to display an alert to the user in a visually appealing way. To achieve this, I am utilizing Bootstrap's alert class. Here is how I am showing the user a div: <div class="alert alert-warning alert-dismissible" role="alert"> Some text ...

The default props defined in the React component's child element are taking precedence over the custom props supplied by the parent component

The font size is being displayed as 20 and the color as 'red', instead of the font size being 12 and the color being 'blue' as specified in the parent component. However, the fontWeight as 'bold' is showing correctly. I have ...

Issue encountered while attempting to pass a function to a child component in React (Uncaught error: TypeError - result is not a function)

How can I pass the result obtained from an API call made in a child component to the parent component? Let's take a look: PARENT COMPONENT: const Parent = () => { function logResult(resultFromAPI) { console.log(resultFromAPI); } ...

Tips on utilizing path variables within JSON paths

I'm attempting to utilize a path variable within a JSON path. The issue I'm facing is that my variable is being added as a new key to the JSON object instead of replacing the path. Here's an Example of My Code Data = { first:{ ...

Reading and writing to a file in a UI automation using JavaScript: Tips and tricks

While running, I need to identify several properties and create a json object that I want to write to a ".json" file and save on disk. var target = UIATarget.localTarget(); var properties = new Object(); var jsonObjectToRecord = {"properties":properties} ...

Executing Cross-Component Communication in Angular 7: A Quick Guide

I've encountered a challenge with a checkbox in the header component. If the checkbox is checked, I need to display an alert message when the application loads. The tricky part is that the checkbox is linked to the home component. Therefore, if I am o ...

Error: The use of "let" as a lexically bound identifier is not permitted

Currently working with vue.js and encountering the error message "Uncaught SyntaxError: let is disallowed as a lexically bound name". When trying to troubleshoot, I'm faced with a blank screen and this error appearing in the console. I've search ...