这是我的app.html结构:
<div class="body">
<div class="content">
<router-outlet></router-outlet>
</div>
<aside>
<!-- aside component here, relative to <router-outlet> -->
</aside>
</div>
如何根据插入路由器插座的组件动态添加组件?
例如:
命名路由器插座可以完成这项工作,但我不想在我的URL中添加额外的语法(插座:路径),因为每个主路由器插座只能有一个旁边的组件......
答案 0 :(得分:1)
我认为实现它的一种方法是使用ComponentFactoryResolver
,如下所示:
@Component({
selector: 'my-app',
template: `
<div class="container">
<div class="content">
<router-outlet></router-outlet>
</div>
<aside>
<template #vcRef></template>
</aside>
</div>
`
})
export class AppComponent {
asideMap = {
'/': ChatboxComponent,
'/home': ChatboxComponent,
'/news': ListNewsComponent
};
@ViewChild('vcRef', { read: ViewContainerRef }) vcRef: ViewContainerRef;
constructor(private router: Router, private resolver: ComponentFactoryResolver) {
router.events
.filter(event => event instanceof NavigationStart)
.subscribe((event) => {
const comp = this.asideMap[event.url];
this.vcRef.clear();
let compRef = this.vcRef.createComponent(this.resolver.resolveComponentFactory(comp));
compRef.instance.param = event.url;
});
}
}
不要忘记将ChatboxComponent
和ListNewsComponent
添加到模块的entryComponents
属性中。
<强> Plunker Example 强>