我正在开发一个项目,我需要动态创建组件并将它们添加到选项卡,但最初我创建了一个包含两个组件的小项目,我想在 div 中动态加载这两个组件
应用模块.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';import{RouterModule, Router, NavigationEnd, ActivatedRoute}from "@angular/router";
import { AppComponent } from './app.component';
import { TestOne, TestTwo } from './my.component';
@NgModule({
declarations: [
AppComponent,
TestOne,
TestTwo
],
imports: [
BrowserModule,
RouterModule.forRoot(
[{
path:"first",component:TestOne
},{
path:"second",component:TestTwo
}]
)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
我的.component.ts
import { Component } from "../../node_modules/@angular/core";
@Component({
selector: 'test-one',
template: '<p>Test One</p>'
})
export class TestOne {}
@Component({
selector: 'test-two',
template: '<p>Test Two</p>'
})
export class TestTwo {}
app.component.ts
import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
import { ActivatedRoute, Router, NavigationEnd } from '../../node_modules/@angular/router';
import { TestOne, TestTwo } from './my.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
entryComponents:[TestOne,TestTwo]
})
export class AppComponent {
title = 'app';
@ViewChild('container', { read: ViewContainerRef }) _vcr:ViewContainerRef;
constructor(private componentFactoryResolver: ComponentFactoryResolver,
private route:ActivatedRoute,private router:Router){
router.events.subscribe(e => {
if(e instanceof NavigationEnd){
console.log((<any>route.firstChild.component).name);
let componentFactory = this.componentFactoryResolver.resolveComponentFactory((<any>route.firstChild.component).name);
this._vcr.createComponent(componentFactory);
}
});
}
}
app.component.html
<ul>
<li>
<h2><a routerLink="/first">test one</a></h2>
</li>
<li>
<h2><a routerLink="/second">test two</a></h2>
</li>
<div #container></div>
</ul>
我收到错误:TestOne 中的错误不能用作入口组件。
我在 app.module 和 app.components 中添加了这两个组件作为 entryComponents,但每次我都遇到同样的问题。
谁能让我知道我错过了什么?