Encountering an error message that says "ERROR TypeError: Cannot read property 'createComponent' of undefined" while trying to implement dynamic components in Angular 2

I am currently facing an issue with dynamically adding components in Angular 4. I have looked at other similar questions for a solution but haven't been able to find one yet. The specific error message I am getting is:

ERROR TypeError: Cannot read property 'createComponent' of undefined

This error occurs when trying to work with dynamic components.

adv.component.ts

import { Component, OnInit, AfterContentInit, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
import { SampleComponent } from '../sample/sample.component';
@Component({
  selector: 'app-adv',
  templateUrl: './adv.component.html',
  styleUrls: ['./adv.component.css']
})
export class AdvComponent implements OnInit, AfterContentInit {
  @ViewChild('container', {read:'ViewContainerRef'}) container;
  constructor(private resolver : ComponentFactoryResolver) { }

  ngOnInit() {
  }

  ngAfterContentInit(){
    const sampleFactory = this.resolver.resolveComponentFactory(SampleComponent);
    this.container.createComponent(sampleFactory);
  }

}

adv.component.html

<div #container></div>

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { AdvComponent } from './adv/adv.component';
import { SampleComponent } from './sample/sample.component';

@NgModule({
  declarations: [
    AppComponent,
    AdvComponent,
    SampleComponent
  ],
  entryComponents:[
    SampleComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Answer №1

Explaining ngAfterViewInit from the documentation:

Executes after Angular has initialized the component's views and child views.

On the other hand, ngAfterContentInit does:

Executes after Angular projects external content into the component's view.

Since the child view is not ready in ngAfterContentInit, it is recommended to move this piece of code:

ngAfterContentInit(){
    const sampleFactory = this.resolver.resolveComponentFactory(SampleComponent);
    this.container.createComponent(sampleFactory);
}

to:

ngAfterViewInit() {
    const sampleFactory = this.resolver.resolveComponentFactory(SampleComponent);
    this.container.createComponent(sampleFactory);
}

Additionally, modify:

@ViewChild('container', {read:'ViewContainerRef'}) container;

to:

@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef 

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

Understanding the data types of functions in TypeScript can be quite important for

What type of information is required after the colon : in this specific function? public saveHistory(log: String): "HERE!" { return async (req: Request, res: Response, next: NextFunction): Promise<Response | void> => { try { ...

Text alignment issue in Material UI Data Grid Component

Currently, I am working with a DataGrid component nested inside a div that is enclosed within a Box component. I am facing issues in centering the content of the DataGrid and styling the header text. The code snippet I'm using is: Blockquote <B ...

AG Grid, efficiently organizing hierarchical data with tree structures and allowing filtering at all levels, not just leaf

My grid is receiving tree formatted data, and I've noticed that when using column filters, they apply to the leaf nodes as well as show parent nodes necessary to provide a path to the leaves. I'm interested in finding a method to allow users to ...

Exploring the World of 3D Rotation with Three.js

I currently have 2 mesh objects - the Anchor and the Rod. The Anchor rotates around the z-axis, as shown in the image. The Rod is designed to only move backward and forwards. You can view the image here: . However, I am struggling to determine the matrix ...

Tips for saving the web address and breaking down each word

Hello, I am familiar with how to store URL parameters using the following JavaScript code. However, I am wondering if there is a way to store each word that comes after a slash in a URL. For example, let's consider the URL: http://localhost:9000/Data ...

Challenges with Primeng Component UI

I am currently working with PrimeNG components, but I'm facing issues with the UI display on the web browser. At this moment, I need to showcase a static dropdown. I have referred to PrimeNG for guidance. Below is the code snippet to implement that c ...

Transmitting HTML content to the browser from the client using Node.js

Quoted from: Book - "Getting MEAN with Mongo, Express.." When it comes to responding to requests in your application by sending HTML to the browser, Express simplifies this process compared to native Node.js. With support for various templating e ...

Errors encountered when using TypeScript with destructured variables and props not being recognized

I have a function that returns data. The object is structured with properties such as headerMenu, page, content, and footer. These properties are defined in DataProps interface. When I try to destructure the data object using the line: const { headerMenu, ...

How to assign a new type to a class in Typescript

I am attempting to re-export a class with an internal type declaration in Typescript. My goal is for the re-exported class to be usable both as a class (with new) and as a type. Below is an example of what I have tried: class XReal { foo() {return 5} } dec ...

Removing a single object from an array of objects using MongooseJS

Hello to all the MongooseJS experts out there! I'm a newcomer to MongooseJS, and I've been trying to solve this problem for the past two days but haven't found a solution yet. Thank you in advance for any help! The Issue with My Delete me ...

Changing the target in tsconfig.json to "es2022" leads to the error message "Property 'xx' is referenced before its initialization.ts(2729)"

My Angular code is filled with instances where I assign a property at its definition like this... public data$ = this.service$.fetchData; constructor(private service$: MyService However, after updating my tsconfig.json target to "es2022", I encountered ...

unable to retrieve element values using class names

I have created multiple h1 elements with the same class names listed below. <h1 class="h1">One</h1> <h1 class="h1">Two</h1> <h1 class="h1">Three</h1> <h1 class="h1">Four</h1> I have also added a button that ...

What is the reason that the 400 status code consistently causes the enter catch block to execute when using axios?

In the frontend of my website, there is a contact form with three fields -> name, email, message. These fields are then sent to the backend using Axios. If a user fails to fill out any of the required fields, they should see a message saying "please f ...

Resolving TypeError: matchesSelector method is not recognized within React component

I am currently integrating masonry-layout from the official website to create a masonry grid within my component. However, I encountered an issue where clicking on a rendered element triggers the error message TypeError: matchesSelector is not a function. ...

What is the best way to transfer a variable from PHP to JavaScript as the actual variable itself, rather than as a string?

I am transferring data from PHP to JavaScript using AJAX. I apply json_encode before sending the data. Here is an example: $data = [ [ "path" => "/TestMenu1", "component" => 'test1', "children" => [[ ...

Encountered an unexpected token error when executing karma-coverage in a project using TypeScript

I have been working on a simple Angular/Typescript project that includes 12 basic unit tests which all pass successfully. However, I am now looking to measure the code coverage of these tests. Despite trying different methods, I have not been able to achie ...

Content formatted with a gap

I wish to include a gap between each sample usage with markdown. For instance: .kick Sarah, .kick John, .kick Mary .setDescription(`**Usage :** \`${settings.prefix}${command.help.name} ${command.help.usage}\`\n**Example :** \`${setting ...

Modify the internal class style to set overflow property to visible for a particular class in PrimeNG

Looking for a way to customize the styles of PrimeNG or Angular2 components? The documentation may be lacking clarity, but you can find more information at this URL: http://www.primefaces.org/primeng/#/dialog So, how do you actually go about changing the ...

JavaScript: Implementing a for loop to dynamically adjust CSS properties

How can I adjust the margin-top property of the ball element when clicking a button? Below is my current code, but it's not working as expected. Can you help? let ballMargin = ball.style.marginTop; moveButton.addEventListener('click', funct ...

Can ngFor be utilized within select elements in Angular?

I'm facing an interesting challenge where I need to display multiple select tags with multiple options each, resulting in a data structure that consists of an array of arrays of objects. <div class="form-group row" *ngIf="myData"> <selec ...