gpt4 book ai didi

javascript - 在 Angular2 中使用动态组件时出现错误 "ERROR TypeError: Cannot read property ' createComponent' of undefined"

转载 作者:行者123 更新时间:2023-11-29 21:01:43 32 4
gpt4 key购买 nike

我正在尝试在 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com