Angular 2 - Get viewContainerRef of a different Component

1,198 views
Skip to first unread message

Sumair Ahmed

unread,
Jul 27, 2017, 11:58:19 AM7/27/17
to Angular and AngularJS discussion
Hi,

I have the following structure:

TabComponent
Navbar
Dashboard

I have a tabComponent with a singleton service that stores the tabs and is injected into tabComponent.

My problem is if i click a new button on the navbar, i want to create a new tab in my TabComponent.

I cannot get the viewContainerRef of the tabComponent from the navbar.  How can i do this?


TabComponent
<ej-tab #mainTabControl id="mainTabControl" [showCloseButton]="true" (beforeActive)="onBeforeTabItemActive($event)">
<ul><li></li></ul>
<div id="tabContent0"><div #tabContent0></div></div>
</ej-tab>

ribbonComponent
export class RibbonComponent {
@ViewChild('mainTabControl', {read: ViewContainerRef}) tab;

constructor(private router: Router, private componentFactory: ComponentFactoryResolver,
private viewContainerRef: ViewContainerRef) {}

handleRibbonEvent(args) {
switch(args.target.id) {

case 'Default_new_business':
let factory = this.componentFactory.resolveComponentFactory(TabComponent);
this.viewContainerRef = this.tab.createComponent(factory);
//ref.instance.createNewTab('dashboard','Dashboard', {});
break;
default:
break;
}
}
}

Zlatko Đurić

unread,
Jul 28, 2017, 1:59:08 AM7/28/17
to Angular and AngularJS discussion
Can't you pass it around like anything else in Angular, via a service? A simple Subject could probably pass this around.

In any case it sounds fishy to pass those around. I assume that there might be a case but I can't think of one right now. What is it that you're trying to achieve? Hook to an event, attach some content, rearrange tabs? None of those sound like a job for another component, like Navbar. Maybe navbar can express a desire for something and your tab manager will do it?

Juri Strumpflohner

unread,
Jul 30, 2017, 2:51:17 AM7/30/17
to Angular and AngularJS discussion
Hi Sumar,

I happen to have just implemented such an example for teaching people about dynamic componente, template outlets and stuff. I'm pretty sure that article would help you as it showcases the same problem you're describing: https://juristr.com/blog/2017/07/ng2-dynamic-tab-component/

Let me know if you need more help :)

Juri
Reply all
Reply to author
Forward
0 new messages