I have something like this in my routes.
const routes: Routes = [
{
path: 'master',
component: MasterComponent,
children: [
{
path: 'first',
component: FirstComponent
},
{
path: 'second',
component: SecondComponent
}
]
}
];
The idea is that when I go to the address http://site/master/*option*
it will render the master component plus whichever component I am putting in *option*
.
The master component has a <router-outlet>
inside of it, and in there it will render the "option" I'm navigating to. That is working perfectly, and rendering just fine. However, what I want to do now is from Master find a value inside the option component I navigated to. An example is a title I will display in Master which varies depending on the "option" component I'm navigating to. Is there any way I can achieve this? Or maybe there's a better way to do it.
I was trying to use ViewChild
or ViewChildren
but both require that you define the type of the Component, and since the component will not always be the same, it's not viable.
CodePudding user response:
You can achieve this with 2 method
Method #1
Use activate
event of router outlet
<!-- master.component.html -->
<router-outlet (activate)="onActivate($event)"></router-outlet>
//master.component.ts
onActivate(componentRef){
console.log(componentRef.title); //access methods and properties of current loaded component
}
Method #2
Add title variable in service and change it in child component
//master.service.ts
title = '';
changeTitle(title) {
this.title = title;
}
//first.component.ts
ngOnInit() {
this.masterService.changeTitle('First');
}