Reputation:
Here is my app.html structure :
<div class="body">
<div class="content">
<router-outlet></router-outlet>
</div>
<aside>
<!-- aside component here, relative to <router-outlet> -->
</aside>
</div>
How can I dynamically add a component inside aside, based on the component inserted in router-outlet ?
For example :
Named router-outlet would do the job, but I dont want to add the extra syntax (outlet:path) inside my URL, as there can only be one aside component per primary router-outlet...
Upvotes: 0
Views: 447
Reputation: 214007
I think one way to achive it is use ComponentFactoryResolver
as shown below:
@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;
});
}
}
Don't forget to add ChatboxComponent
and ListNewsComponent
to entryComponents
property of your module.
Upvotes: 1