我正在尝试在 angular4 中动态添加组件。 我检查了其他问题,但我找不到解决方案。 我得到了错误
ERROR TypeError: Cannot read property 'createComponent' of undefined
关于动态组件。
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 { }
最佳答案
关于 ngAfterViewInit
docs :
Respond after Angular initializes the component's views and child views.
当 ngAfterContentInit
时:
Respond after Angular projects external content into the component's view.
所以 subview 在ngAfterContentInit
中还没有准备好,所以移动这部分
ngAfterContentInit(){
const sampleFactory = this.resolver.resolveComponentFactory(SampleComponent);
this.container.createComponent(sampleFactory);
}
到
ngAfterViewInit() {
const sampleFactory = this.resolver.resolveComponentFactory(SampleComponent);
this.container.createComponent(sampleFactory);
}
同时改变:
@ViewChild('container', {read:'ViewContainerRef'}) container;
到
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef
关于javascript - 在 Angular2 中使用动态组件时出现错误 "ERROR TypeError: Cannot read property ' createComponent' of undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46115320/