我试图在angular4中动态添加组件。 我检查了其他问题,但我无法找到解决方案。 我收到了错误
错误TypeError:无法读取未定义的属性“createComponent”
关于动态组件。
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 { }
答案 0 :(得分:2)
关于docs中的ngAfterViewInit
:
在Angular初始化组件的视图和子视图后做出响应 视图。
while ngAfterContentInit
:
在Angular将外部内容投射到组件中之后做出响应 图。
因此,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