Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error "ERROR TypeError: Cannot read property 'createComponent' of undefined" when work with dynamic component in Angular2

I am trying to add the components dynamically in angular4. I checked with other questions, But i cant find solution. I got the error

ERROR TypeError: Cannot read property 'createComponent' of undefined

on 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 { }
like image 669
Gmv Avatar asked Sep 08 '17 11:09

Gmv


1 Answers

About ngAfterViewInit in docs:

Respond after Angular initializes the component's views and child views.

while ngAfterContentInit:

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

So the child view is not ready in ngAfterContentInit, so move this part

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

to

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

Also change:

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

to

@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef 
like image 108
Vega Avatar answered Nov 10 '22 21:11

Vega