Using Angular 4's ngComponentOutlet to showcase ContentChildren that are dynamically changing

My main objective is to create a unique container component with a dynamic list of customized card components that can be accessed individually (instead of as a group using ng-content).

<custom-card-holder>
    <custom-card></custom-card>
    <custom-card></custom-card>
    ...
    <custom-card></custom-card>
</custom-card-holder>

My goal is to use ContentChildren query to fetch each child component and place it inside a styled div within the custom card holder.

The aim is to display each content child in its own styled div to ensure it fits neatly inside the holder.

I have experimented with TemplateOutlet and some other options, but ComponentOutlet seems like the most promising choice.

I want to keep the code above clean without any unnecessary clutter. I realize that data can simply be input and the component used without transclusion, but this could make the interface more complex for others to understand.

Answer №1

Thanks to @Arivinds valuable insight, a solution was found to address a syntax issue and partially resolve the original problem. The key takeaway from his comment can be found here.

  1. It should be noted that ngComponentOutlet requires a Type or Class, not an instance.

  2. A workaround involved nesting the Class within a list alongside the instance:

    cardList = [{ component: CardClass, context: instance }]

To address this, a new CardHolder component was introduced. Its template consisted of a simple

<ng-content></ng-content>
, replacing the need for the Card class in the cardList. Subsequently, the ngComponentOutlet's content property was utilized to project the actual Card within the CardHolder.

cardList: any[] = [
  {
    type: CardHolder,
    context: {}
  }
];

`<div #scrollItem class="item" *ngFor="let card of cardList">
  <ng-container *ngComponentOutlet="card.type;content: card.context;"></ng-container>
</div>`

An important note: While working with the content property of ngComponentOutlet, it is vital to bear in mind that it accepts a Node when querying for ContentChildren. In this case, accessing the nativeElement through double square brackets proved beneficial.

`ngAfterContentInit(){
    this.cardList = this.cards.toArray().map((card) => {
       return {type: CardHolder, context: [[card.nativeElement]]};
    })
}`

This approach aims to assist others facing similar challenges in their projects.

Note: The functionality allowing for inputs on dynamic components is reportedly under development but not yet fully implemented.

Note: It is recommended to include any dynamic components in the entryComponents array of the NgModule.

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 method for displaying script commands within package.json files?

With a multitude of repositories, each one unique in its setup, I find myself constantly referencing the package.json file to double-check the scripts. "scripts": { "start": "npm run dev" "build:dev": "N ...

The type definition file for 'jest' cannot be located, despite the fact that jest has been successfully installed

SOLUTION STRATEGY: If you encounter a similar issue and are looking for a more comprehensive solution rather than quick fixes, consider recreating the repository. While it involves more effort initially, it can prevent future issues. In my case, the repos ...

The deployment of the remix is unsuccessful in Vercel, even though it functions perfectly during development. The error message states that 'AbortController' is not

I'm new to React and could use some assistance with a deployment issue on Vercel. Any ideas on why this is failing? I haven't explicitly used AbortController anywhere, so I'm suspecting it might be related to one of the installed packages? ...

Creating validation for an autosave reactive form in Angular 2: A step-by-step guide

Seeking advice on implementing an autosave feature for a reactive Angular 2 form. The idea is that as the user types in values, the form should automatically save if the input is valid. Below is the code snippet: export class BusinessFoundationsPage { ...

It is not possible to import Angular MockBackend with a production build

In my Angular application, I have set up a mock backend for use in end-to-end tests. To determine whether to use the mock backend or an actual HTTP backend service, I created a factory function. The factory function checks if the build is for production a ...

Exploring the functionality of two-way data binding in Angular - a beginner's guide

Transitioning from a different framework and switching from JavaScript to Angular & TypeScript has left me feeling confused about how to efficiently share data/values between components. ...

Storing a variable in Cypress with Typescript for use in the afterEach teardown step

Throughout my test cases, I store data in a variable to be used consistently. The variable maintains its value until the very end of the test, but when trying to access it in the @afterEach teardown function for global clean up, it appears empty. It seems ...

Exploring the world of Angular CLI testing and the versatility of

Struggling with integrating Angular CLI's test framework and enum types? When creating an enum like the following (found in someenum.ts): const enum SomeEnum { Val0, Val1 } Utilizing it in this way (in app.component.ts): private someEnum = Some ...

Learn how to dynamically enable or disable the add and remove buttons in the PrimeNG PickList using Angular 2

I'm currently learning Angular 2 and I'm working on creating a dual list box using PrimeNG's pickList component (https://www.primefaces.org/primeng/#/picklist). Within the pickList, I have table data with 3 columns, along with ADD and REMO ...

Error in Angular: Unable to Access Property '..' of null

Having an issue with my Angular project where I keep getting an error message saying "cannot read property of '...' of undefined" whenever I select an employee from the combo box. The '...' represents the index of the selected employee. ...

Utilize the TypeScript Compiler API to extract the Type Alias Declaration Node from a Type Reference Node

Currently, I am utilizing ts-morph library which makes use of the TS Compiler API. Here is an example of my code: export type Foo = string export const foo: Foo = 'bar' Whenever I try to find the type for the export of foo, it returns string. H ...

Creating applications with Angular2 and TypeScript is possible even without utilizing NPM for development

I've seen all the guides recommend installing npm, but I'm determined to find an alternative method. I found Angular2 files available here, however, none of them are in TypeScript code. What is the best course of action? Do I need Angular2.ts, ...

Unable to execute karma test cases as a result of ngOnDestroy being inaccessible

I have a component structured as follows: export class InkbarComponent implements AfterViewInit, OnDestroy { resizeListener: any; constructor(private _renderer: Renderer, private _elementRef: ElementRef, public renderer: Renderer) { } ngAfter ...

Configuring rows in React datagrid

I am working on a component where I receive data from the backend and attempt to populate a DataGrid with it. Below is the code for this component: export const CompaniesHouseContainer: React.FC<Props> = () => { const classes = useStyl ...

What is the process for importing an mp3 file into a TypeScript project?

I'm currently working on a web application using React and TypeScript. My current challenge involves importing an mp3 file for use with the use-sound library, but I keep encountering this error in TypeScript: "Cannot find module '../../as ...

Data binding with ngModel is contingent on certain conditions

I am facing an issue with conditional data binding using ngModel in Angular4. Let me explain further: I have a small form: <form-question-radio [(ngModel)]="model['q4']" name="question" [options]="[{value:true, label:'Yes'}, ...

Chrome stack router outlet and the utilization of the Angular back button

I'm experiencing an issue with the back button on Chrome while using Angular 14. When I return to a previous page (URL), instead of deleting the current page components, it keeps adding more and more as I continue to press the back button (the deeper ...

ng-for loop not properly rendering array of collections in table cells

I've been working on developing a MEAN Stack application that deals with mongoDB data related to hostels. hostels { "_id" : ObjectId("5e3c21c03d8d54b35af796ed"), "Hostel" : "The traveler's Lodge", "Rooms" : 23, "Customer" : [ { ...

React Native Redux Toolkit: Despite the state showing a non-serializable value, my object is confirmed to be serializable

I recently upgraded my traditional react-native with redux App to the modern redux-toolkit and encountered an error: A non-serializable value was found in the state, in the path: `currentUserSessionData.data`. Value:, CurrentUserSessionData { "isOnb ...

What is the process for implementing a type hint for a custom Chai assertion?

As part of my typescript project, I decided to create a custom assertion for the chai assertion library. Here is how I implemented it: // ./tests/assertions/assertTimestamp.ts import moment = require("moment"); import {Moment} from "moment"; const {Asser ...