Send a collection of Angular components to an HTML template by passing them as an

Scenario :- I am working on a small Angular application with only two tabs displayed on a single screen, deployed independently as static assets in an AWS S3 bucket.

Situation :- Within one of my Angular (version 12) container components, I have lengthy markup that includes duplicated code for creating a grid. The structure looks like this:

<div class="col">
        <div class="row">
          <div class="col">{{aStringTitle}}</div>
        </div>
        <div class="row">
          <div class="col mt-2">
            {{differentMarkupForEachColumn}}
          </div>
        </div>
      </div>

Objective :- My goal is to display these columns using *ngFor by passing an array of the following structure:

    [
      {name: 'First Ng Component', component: <SmallAngularComponent>},
      {name: 'Second Ng Component', component: <AnotherSmallAngularComponent>},
      ...... and so on up to 7-8 smaller Angular components    
    ]

When I searched angular.io, I was unable to find a suitable example in the template documentation.

Main question :- How can I pass an array of Angular components to the template of a parent Angular component?

Preference :- Although there is an alternative solution mentioned in this answer, I specifically aim to render proper Angular components and not generic HTML elements.

Answer №1

It seems like you're looking to dynamically generate these elements within your HTML.

To achieve this, you can utilize the NgComponentOutlet directive (check out more details here).

Your implementation would resemble the following:

component.ts

components = [
  { name: 'First Ng Component', component: SmallAngularComponent },
  { name: 'Second Ng Component', component: AnotherSmallAngularComponent },
  // ...... and so forth, up to 7-8 smaller angular components    
];

You may have noticed that there's no need for <> around the components.

component.html

<ng-container *ngFor="let entry of components">
  <div class="col">
    <div class="row">
      <div class="col">{{ entry.name }}</div>
    </div>
    <div class="row">
      <div class="col mt-2">
        <ng-container *ngComponentOutlet="entry.component"></ng-container>
      </div>
    </div>
  </div>
</ng-container>

If you require passing parameters to different components, you can refer to this resource here, or consider creating these components programmatically.

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

Function in Typescript that accepts either a single object or an array of objects

We frequently use a simple function declaration where the function can accept either a single object or an array of objects of a certain type. The basic declaration looks like this: interface ISomeInterface { name: string; } class SomeClass { pu ...

Using a single Material Autocomplete input to handle two values within Angular

Looking to implement a search feature using Material's autocomplete that can filter by either user name or user ID. The current implementation is partially functional in this Stackblitz. When selecting a user name from the autocomplete options with a ...

Using Typescript to prevent the usage of await with Tslint

Can Tslint be utilized to restrict the usage of Typescript's await feature? If not, are there alternative linters available for this purpose? ...

Create a new TypeScript object without any initial properties, then proceed to define its attributes

Working on honing my skills with Angular Forms utilizing the template-driven approach. My goal is to construct a user interface to display the output of my data in this structure: <hr> <div class="well well-lg"> ...

Incorporating JointJS into your project

After following the guide on How to integrate JointJS with an Angular CLI application, I encountered a problem when starting the project: Module not found: Error: Can't resolve './node_modules/jointjs/dist/joint.js' I attempted to change t ...

Angular 5 - capturing form inputs - activating event upon selecting suggested values

When I click on suggested values below the input field, the (click)="doSomething()" event doesn't fire. How do I handle this issue? I would like to be able to type something in the input field and then have an event triggered when clicking on the su ...

Having trouble with an external JavaScript file in Angular 5?

Recently, I decided to delve into the world of Angular and started my journey with angular5 by following this tutorial. Currently, I am in the process of converting a traditional HTML template into an Angular5 version but have encountered some challenges ...

Having trouble with filtering an array using the some() method of another array?

When utilizing the code below, my goal is to filter the first array by checking if the item's id exists in the second array. However, I am encountering an issue where the result is coming back empty. dialogRef.afterClosed().subscribe((airlines: Airli ...

ngx-bootstrap encountered an issue: TypeError - _co.openModal is unavailable as a function

Just starting out with ngx-bootstrap, I was attempting to create a modal using the instructions from this site : However, I encountered the following error: ERROR TypeError: _co.openModal is not a function Here are some code snippets: //app.component ...

Switch Angular checkbox to display string values instead of boolean true/false

My task is to create three checkboxes in a form with values toggling between "optin" and "optout" as I check/uncheck the checkboxes. Additionally, all checkboxes should be checked by default for the "optin" value. I'm struggling to find a solution, an ...

Error encountered during npm installation - EPERM: Operation not allowed

Today's challenge began when attempting to run the angular4 project and encountering this error: npm install eperm operation not permitted. In an effort to resolve it, I decided to delete the node modules folder and try again. However, upon running np ...

The type of props injected by WithStyles

When working on my class component, I utilize material UI withStyles to inject classes as a property. export default withStyles(styles)(myComponent) In this process, const styles = ( (theme:Theme) => createStyles({className:CSS_PROPERTIES}) I am att ...

Tips on obtaining the current date format (e.g. dd/mm/yyyy or mm/dd/yyyy) on the client side

I am currently working with the datepicker control, and I need to adjust the date format based on my browser's settings - either dd/mm/yyyy or mm/dd/yyyy. For example: if my browser date is 22/06/2019, then I should use "dd/MM/yyyy" format in the dat ...

Angular Recurring Request

Currently, I am using Angular5 and making requests every 5 seconds to check the status of a task. However, I would like to implement a more flexible condition where if the request receives a status code of 202, continue sending requests, but if it receives ...

React-querybuilder experiencing issues with validator functionality

While utilizing the react-querybuilder, I have encountered an issue with field validation not functioning correctly. Upon reviewing this StackBlitz, it appears that when clicking on Rule and checking all fields, there are no errors present. export const fi ...

Creating an NPM package using Visual Studio 2017: A Step-by-Step Guide

I enjoy developing and publishing NPM packages using Visual Studio 2017. My preferred method is using TypeScript to generate the JavaScript files. Which project template would be best suited for this particular project? ...

A guide on incorporating Angular Material into a monolithic application in JHipster version 7.6.0

Hello everyone, I have an application built with jHipster 7.6.0 and I am trying to integrate Angular Material into it. When I run the command ng add @angular/material, I encounter this error: https://i.stack.imgur.com/J3ErS.png The issue I am facing wit ...

How to fix patchValue not functioning in an angular formArray?

Inside my Angular application, I am creating a formArray within a form. However, when I try to patch an object containing tasks with values as an array, it seems that this property is being ignored and not set. Interestingly, the first name is changed as ...

The function modal() is not recognized; ensure bootbox is properly defined

After installing bootbox with "npm install bootbox --save" and adding it to angular.json "scripts": [ "./node_modules/jquery/dist/jquery.min.js", "./node_modules/bootstrap/dist/js/bootstrap.min.js", "./node_module ...

Leveraging Angular's HTTPClients: merging multiple HTTP requests with Observables to optimize asynchronous operations

In my HTML code, I have the following: <ng-container *ngIf="lstSearchResults|async as resultList; else searching"> ... <cdk-virtual-scroll-viewport class="scroll-container"> <div *cdkVirtualFor="let search of resultList" class="card ...