我正在一个需要动态创建组件并将其添加到选项卡的项目中,但是最初我创建了一个包含两个组件的小项目,我想在div中动态加载这两个组件
App.module.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 {
}
my.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,但是每次遇到相同的问题时。
有人可以让我知道我在想什么吗?