I repeatedly run into a situation where I\'d like to access a child component existing on the other side of a router outlet rather than a selector:
Like:
<
The approach by Madhu works if you are not reattaching to a route. It appears that activate does not get run on the re-route.
There is a read only property on router-outlet that contains the current component.
example:
@Component({
selector: 'my-app',
template: `<h3 class="title">Basic Angular 2</h3>
<button (click)="identifyYourself()"></button>
<router-outlet></router-outlet>
`
})
export class AppComponent {
@ViewChild(RouterOutlet) outlet;
constructor(){}
identifyYourself() {
if (outlet && outlet.component) {
(outlet.component as IIdentify).identify();
}
}
}
@Component({
selector: 'my-app',
template: `<h3 class="title">Dashboard</h3>
`
})
export class DashboardComponent implements IIdentify{
constructor(){}
identify(){
console.log('Hello, I'm the dashboard!');
}
}
interface IIdentify {
identify:()=>void;
}
See an example here Check this example out
https://stackblitz.com/edit/angular-zluvgc
You may tap into activate event to get reference of instantiated component inside the router outlet.
excerpt from RouterOutlet Docs
A router outlet will emit an activate event any time a new component is being instantiated, and a deactivate event when it is being destroyed.
example
@Component({
selector: 'my-app',
template: `<h3 class="title">Basic Angular 2</h3>
<router-outlet (activate)="onActivate($event)" ></router-outlet>
`
})
export class AppComponent {
constructor(){}
onActivate(componentRef){
componentRef.sayhello();
}
}
@Component({
selector: 'my-app',
template: `<h3 class="title">Dashboard</h3>
`
})
export class DashboardComponent {
constructor(){}
sayhello(){
console.log('hello!!');
}
}
Here is the Plunker!!
Hope this helps!!