Retrieving automatically generated module

In my setup, there is a component that takes in some data and dynamically generates other components using ngx-charts.

This specific part acts as the directive

@Directive({
  selector: '[ad-host]',
})
export class PresentationDirective {
  constructor(public viewContainerRef: ViewContainerRef) {
  }
}

The template structure is quite straightforward

<div class="presentation">
  <ng-template ad-host></ng-template>
</div>

Now moving on to the main component section

presentations: Presentation[] = new Array();
components: any[] = new Array();

During initialization, I iterate through an array of data and execute the loadComponent function

ngOnInit() {
  const temp = this.simulationResponse['presentations'];
  for (const presentation of temp) {
    this.presentations.push(presentation);
    this.loadComponent(this.getComponent(presentation['type']), 
    presentation['data']);
  }
}

The getComponent function simply returns the necessary component based on its type to be used by loadComponent

getComponent(componentType: string) {
  switch (componentType) {
    case 'PIE': {
      return PieChartComponent;
    }
    case 'BAR': {
      return BarChartComponent;
    }
  }
}

Within loadComponent, a new component is created each time it's called with the respective data needed for graphic rendering

loadComponent(component: any, data: any) {
  const componentFactory = 
  this.componentFactoryResolver.resolveComponentFactory(component);
  const viewContainerRef = this.adHost.viewContainerRef;
  const componentRef = 
  viewContainerRef.createComponent(componentFactory);
  this.components.push(componentRef);
  (<AddData>componentRef.instance).single = data;
}

Whenever there are changes in the data, updatePresentations function is triggered

ngOnChanges() {
  this.updatePresentations();
}

The struggle arises within updatePresentations, specifically when trying to assign data, resulting in two errors

updatePresentations() {
  const viewContainerRef = this.adHost.viewContainerRef;
  for (let i = 0; i < viewContainerRef.length; i++) {
    const componentRef = viewContainerRef.get(i);
    const tmp = this.presentations[i];
    (<AddData>componentRef.instance).single = tmp['data'];
  }
}

The first error pertains to assigning values, while the second one points out a missing property 'includes'

Error message example - ERROR in src/app/simulator/presentation/presentation.component.ts(71,7): >error TS2322: Type '{}' is not assignable to type 'any[]'.

Another error example - Property 'includes' is missing in type '{}'. src/app/simulator/presentation/presentation.component.ts(71,30): error >TS2339: Property 'instance' does not exist on type 'ViewRef'.

The struggle intensifies with the latter error regarding the 'instance' property from ViewRef

Despite efforts and thorough checks, I am unable to resolve this issue. Any insights or assistance would be greatly appreciated.

Additional Reference:

The development process was heavily influenced by this segment of the Angular guide https://angular.io/guide/dynamic-component-loader

Answer №1

Although I'm not well-versed in Angular, it seems like @yurzui was suggesting that viewContainerRef.get(i) is returning a ViewRef rather than the desired ComponentRef; you can refer to the official documentation. Have you considered using this.components[i] instead?

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

Challenge Encountered with Create-React-App TypeScript Template: Generating JS Files Instead of TSX Files

Encountering a problem setting up a new React application with TypeScript using the Create-React-App template. Followed the guidelines on the official documentation (https://create-react-app.dev/docs/adding-typescript/) and ran the command below: npx creat ...

The error encountered during parsing the module for Next.js, Webpack, and TypeScript files (.ts, .tsx) was due to an unexpected token

Here is the content of my next.config.mjs file: export default { webpack: (config) => { // Find rules that includes current directory const rulesWithCurrentDir = config.module.rules.filter((rule) => rule.include && rule.include.incl ...

What causes the failure of Angular 2 RC.6 routing when bundled with ngc + Rollup?

I have been exploring the new AOT Compiling feature in RC.6, but I have encountered a stumbling block. While I can successfully create a bundle using ngc => Rollup => Babel, I keep getting multiple warnings every time I run Rollup: The 'this&ap ...

How can I dynamically reference two template HTML files (one for mobile and one for desktop) within a single component in Angular 6?

Here is the approach I have taken. Organizational structure mobile-view.component.html <p> This content is for mobile view </p> desktop-view.component.html <p> This content is for desktop view </p> mobile.component.ts import ...

Node corrupting images during upload

I've been facing an issue with corrupted images when uploading them via Next.js API routes using Formidable. When submitting a form from my React component, I'm utilizing the following functions: const fileUpload = async (file: File) => ...

A Guide to Catching Targeted React Notifications in Sentry using Next.js

In my Next.js application, I have implemented Sentry for error tracking. While I have successfully set up Sentry to capture errors within my try/catch blocks, I am currently struggling with capturing specific errors and warnings at a global level in my sen ...

nativescript input value binding

<StackLayout> <Label text="Enter the station name:"></Label> <TextField hint="Station name" col="0" [ngModel]="stationName" (ngModelChange)="stationTyping($event)"></TextField> </StackLayout> An error is occurri ...

Tips on managing ajaxStart and ajaxStop events the Angular2 way

I am seeking a way to trigger events similar to JQuery's ajaxStart and ajaxStop. While I found a partial solution on how to set default HTTP headers in Angular 2 here, I have managed to handle the ajaxStart event for now. Does anyone have any soluti ...

Enhancing the Look of Typeahead in ng-bootstrap

I'm finding it difficult to customize the appearance of the dropdown menu in ng bootstrap typeahead. The input styling works fine (the component only includes an input/typeahead), but I am unable to style the dropdown. I've tried using both the ...

Determining the height of dynamically rendered child elements in a React application

Looking for a way to dynamically adjust the heights of elements based on other element heights? Struggling with getting references to the "source" objects without ending up in an infinite loop? Here's what I've attempted so far. TimelineData cons ...

What is the best way to define this.someProperty in a React component using TypeScript?

I'm encountering an issue with TS2339: Property 'someProperty' does not exist on type ''. I am attempting to add a new property to my React component using this.someProperty. interface MyComponentState { allClear: boo ...

What is the best way to remove query string parameters prior to running a function when a button is clicked?

I'm facing an issue trying to implement a button that filters events based on their tags. The problem arises when the tag value in the query string parameter does not clear when other buttons are clicked. Instead, the new filter tag value adds up with ...

Determining the data type of a particular key within a generic type using TypeScript

I am facing a challenge in achieving the desired complex type functionality with my custom-built generic function called updateArray: // Updates an object array at the specified update key with the update value, // if the specified test key matches the tes ...

When trying to construct a URL in a Next.js Appwrite project, a "TypeError" may occur, but it works perfectly fine when the URL is provided directly

I am currently following a tutorial on YouTube by JS Mastery about their HealthCare application using Next.js and Appwrite. I have obtained my API keys from the Appwrite cloud and added them to the .env.local file. However, upon running my project, I encou ...

Trying to figure out how to avoid HTML characters in AngularJS? I've come across suggestions to use ng-bind / ng-sanitize for escaping HTML, but I'm struggling to put

As a newcomer to Angular Js, I recently utilized ngx-editor to create a text-area with various formatting styles. However, upon submitting the content, I noticed that HTML tags were also being displayed. I understand that these tags appear when using diffe ...

Launching a Dialog in Angular upon selection of an option

Within my application, I have a mat-form-field that includes a mat-option. My goal is for a dialog to open whenever I select an element from the mat-option. However, at the moment, nothing happens when I make a selection. What steps should I take to resolv ...

The Kendo-datepicker always excludes the number zero in the day section

When I try to enter the date: 5/01/2017 The first zero in the days section is always missing when using kendo-date-picker, resulting in the following date: 5/12/17 In my HTML code: <kendo-datepicker [min]="min" [max] ...

Issues have been encountered with Angular 5 when trying to make required form fields work properly

Just created my first Angular app using Angular 5! Currently following the documentation at: https://angular.io/guide/form-validation. Below is the form I have set up: <form class="form-container"> <mat-form-field> <input matInput pl ...

Unable to iterate over a 2D array using 'rows' in JavaScript or TypeScript

Imagine I need to generate a 2D array with this specific structure: [0, 1, 1, 1] [1, 0, 0, 0] [1, 0, 0, 0] To achieve this, I first initialized a 2D array with 0 values: function createGrid(m: number, n: number): number { let grid: number[][] = new Ar ...

Tips for leveraging stage 3 functionalities in TypeScript?

Array.prototype.at() is currently in the proposal stage 3. Even after adding "lib": ["ESNext"] to my tsconfig.json, I encountered the error: Property 'at' does not exist on type 'number[]'. Could you shed some light ...