Is it possible for an object literal to include a property that can be rendered using ngComponentOutlet?

When attempting to render each component using ngComponentOutlet in a specific column layout with subsequent styling, the component property within widgetsByCol is returning null in the HTML, even though the components are visible when logging them through console.log(). (I aim to dynamically render the components without defining the widgets as I have currently done).

The TypeScript code snippet is provided below:

export class WidgetListComponent implements OnInit {
  widgets: WidgetInterface[] = [
    { component: Test1Component, layoutCol: 1 },
    { component: Test2Component, layoutCol: 2 },
    { component: Test3Component, layoutCol: 3 },
    { component: Test3Component, layoutCol: 2 }
  ];

  widgetsByCol = {};

  ngOnInit(): void {
    for (const widget of this.widgets) {
      const { layoutCol, component } = widget;
      if (!this.widgetsByCol[layoutCol]) {
        this.widgetsByCol[layoutCol] = [];
      }
      this.widgetsByCol[layoutCol].push(component);
    }

    console.log('this.widgetsByCol', this.widgetsByCol);
  }
}

The corresponding HTML snippet is presented below:

{{widgetsByCol | json}}
<div *ngFor="let col of widgetsByCol | keyvalue">
  <div *ngFor="let widget of col.value">
    <ng-container *ngComponentOutlet="widget.component"> </ng-container>
  </div>
</div>

The output of {{widgetsByCol | json}} displays: { "1": [ null ], "2": [ null, null ], "3": [ null ] } However, the console.log provides the following result:

{
  1: [Test1Component],
  2: [Teste2Component, Teste3Component],
  3: [Test3Component]
}

This inconsistency raises the question of what might be causing this issue. Any insight would be greatly appreciated. Thank you.

Answer №1

Your code is almost there. There seems to be a small error in your template. Instead of widget.component, try using widget.

<ng-container *ngComponentOutlet="widget"></ng-container>

The discrepancy you're seeing between the console output and the json pipe output is because the json pipe stringifies the object. You'd get the same result if you used JSON.stringify() yourself:

console.log('this.widgetsByCol (stringified)', JSON.stringify(this.widgetsByCol));
// {"1":[null],"2":[null,null],"3":[null]}

Check out the StackBlitz example here.

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

I attempted to retrieve the id field of a jsonwebtoken following the user's login, but unfortunately, I was unable to access it

While working on the backend of my application, I encountered an issue trying to save the id field from a JSON Web Token (JWT) to an item that I created after a user logs in. Although I am able to log the JWT information successfully, I'm facing diffi ...

To set up Ionic on your project, run the command `npm install

After setting up a new Ionic project, I included the Android platform using the command ionic cordova platform add android. This action added the following entry in the config.xml file: <engine name="android" spec="~6.1.2" /> Prior to this, I came ...

Cypress: Conducting Test with Custom Timezone Setting on Windows

My testing environment was set up to run in UTC time zone. I utilized cy.clock() to initialize a date-time in UTC format, which the Web App will then display as the current browser date-time in UTC. In order to achieve this, I ensured TZ=UTC in my environ ...

Advanced filtering of arrays in JavaScript

The data structure I am working with consists of nested arrays of objects, each containing further nested arrays ad infinitum. Imagine deep nesting levels. Let me illustrate my goal with an example. I have a collection of groups. Each group contains heroe ...

Updating Angular components by consolidating multiple inputs and outputs into a unified configuration object

When I develop components, they often begin with numerous @Input and @Output properties. However, as I continue to add more properties, I find it beneficial to transition to utilizing a single config object as the input. For instance, consider a component ...

What is the best way to combine two objects in Angular?

How can I merge objects in Angular 2? Object Response 1 0:Object 1:Object 2:Object 3:Object Object Response 2 0:Object 1:Object 2:Object 3:Object MyComponent Component resultdata :any=Array; fooddrinks_data_func(Defaultparams){ return this.Ci ...

Issue: (SystemJS) XHR error (404) encountered in Angular2 Plnkrsandbox

The issue: https://i.sstatic.net/jUKBU.png https://plnkr.co/edit/910M73kwYKc8xPlSIU57?p=preview index <!DOCTYPE html> <html> <head> <base href="/"> <title>Angular 2.1.2 + TypeScript Starter Kit</title> <met ...

Issue: React cannot render Objects as children (received: [object Promise]). If you intended to display multiple children, please use an array instead. (Next)

My dilemma is this: I am trying to display my GitHub repositories on a React component, but I keep encountering the following error: Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, u ...

What is the correct way to handle Vue props that include a dash in their name?

I am currently working on a project using Vue. Following the guidelines of eslint, I am restricted from naming props in camel case. If I try to do so, it triggers a warning saying Attribute ':clientId' must be hyphenated. eslint vue/attribute-hyp ...

One function in Typescript lodash is missing a default export

Is there a way to import just one function from lodash? I attempted it like this: import get from 'lodash/get'; Even after installing both lodash and @types/lodash, I encountered the following error message: @types/lodash/get/index"' ha ...

Having trouble bringing my custom-built Angular module into my Angular application

Currently considering the utilization of this Yeoman generator as a starting point for a small project that will contain several reusable form components to be published. The generator constructs a module and an example component, directive, pipe, and serv ...

Ways to confirm if a user has previously participated in a poll?

SCENARIO: At present, I am storing an array of objects within the User model to track all the votes cast by the user. Here is a glimpse of the model structure: var schema = new Schema({ firstName: {type: String, required: true}, lastName: {type: ...

Generate a new data type based on the value of a single attribute within a collection of objects

Is there a way to extract a specific property of a combined type and generate a new type from it? Consider the following example: type Actions = | { type: "ADD_COLUMN"; newColumnIndex: number; column: SelectorColumnData; } | { type: ...

Angular 2 Issue: Error Message "Cannot bind to 'ngModel'" arises after FormsModule is added to app.module

I've been struggling with the data binding aspect of this tutorial for over a day now. Here's the link to the tutorial: https://angular.io/docs/ts/latest/tutorial/toh-pt1.html The error I keep encountering is: Unhandled Promise rejection: Tem ...

Encountering Failures with 'npm install' on Specific Repositories

I recently acquired a bundle of Angular/Bootstrap4 templates from a source link to experiment with. However, I am encountering difficulties with the npm install step. After downloading the source and extracting the angular2seed project, I attempted the npm ...

Which is better: Angular module for each page or component for each page?

We are getting started with Angular 8 and have a vision for a web application that includes: A navigation bar at the top with dropdown menu items leading to different UI pages. The main section will display each page, such as: - Sales section ...

Issue: Failed to locate module @angular/core

When attempting to run an Angular 4 application, I consistently encounter the following error: ERROR in Could not resolve module @angular/core There are no additional errors present. There are no dependency issues whatsoever as @angular/core is located i ...

Unable to navigate beyond the boundaries of an app

I am currently facing an issue with my authentication service where it redirects to the identity server in case of certain errors. I attempted to achieve this using window.location.href = environment.authCodeFlowIssuer;, however, an error occurred: Ref ...

Leverage properties within the storybook component template

When utilizing a class component in a narrative, it allows you to transmit properties as arguments: const Template: Story<MyComponent> = (args) => ({ props: args, component: MyComponent, }) export const Default = Template.bind({}); export co ...

Exploring the Power of Modules in NestJS

Having trouble with this error - anyone know why? [Nest] 556 - 2020-06-10 18:52:55 [ExceptionHandler] Nest can't resolve dependencies of the JwtService (?). Check that JWT_MODULE_OPTIONS at index [0] is available in the JwtModule context. Possib ...