Reputation:
I want to change a certain heading according to the current url in Angular. So component.ts looks like this:
import {Router} from '@angular/router';
//code
public name: string
constructor(
public router: Router
) {}
getName()
{
if(this.router.url === "/some_list")
{this.name = "List"}
else if(this.router.url === "/detail")
{this.name = "Detail"}
}
And then
<a>{{this.name}}</a>
The existing answers, like How to detect a route change in Angular? could not tell me how to do something after a change in routing (change = true or false). So how can I run this function whenever the url changes, so that the heading is according to the current view?
Upvotes: 16
Views: 33744
Reputation: 2384
After observing some issues in the comment I thought I should post this as an alternative solution if it helps someone. We will cater 2 issues in this solution:
For that, instead of using OnInit
it is better to handle it in the constructor as it is better and will be checked earlier.
constructor(private router: Router) {
this.router.events.subscribe((event: any) => {
if (event instanceof NavigationEnd) {
// handle NavigationEnd event here
console.log(event.url);
}
});
}
Upvotes: 1
Reputation: 22213
Try like this:
.html
<a routerLinkActive="active" routerLink="/some_list">Home</a> |
<a routerLinkActive="active" routerLink="/detail">Catalog</a>
<router-outlet (activate)="getName()"></router-outlet>
.ts
getName() {
if (this.router.url.includes("some_list")) {
this.name = "some_list";
} else if (this.router.url.includes("detail")) {
this.name = "detail";
}
alert(this.name);
}
Upvotes: 2
Reputation: 38094
As a good practice you should have one component per route.
RouterModule.forRoot([
{ path: 'products', component: DetailComponent },
{ path: 'shopping-cart', component: SomelistComponent }
])
If you keep to this practice, then you will have a separation of concern.
And then according to the route you just set header for your component.
You can read more about routing here.
Upvotes: 2
Reputation: 3387
Go this StackBlitz link
On every navigation start event of router you can get url and fire function. in you app.component.ts
ngOnInit(){
this.router.events.subscribe(event =>{
if (event instanceof NavigationStart){
console.log(event.url)
this.routerChangeMethod(event.url);
}
})
}
routerChangeMethod(url){
this.title = url;
}
Yout app.component.html is..
{{title}}
<router-outlet></router-outlet>
Upvotes: 7
Reputation: 7156
You can subscribe
to router event
in the app.component.ts
.
It will fire every time you change the route
.
constructor(location: Location, router: Router) {
// decide what to do when this event is triggered.
router.events.subscribe(val => {
if (location.path() != "/something") {
// do something
} else {
// do something else
}
});
}
Try this if it is calling multiple times
router.events.filter(event => event instanceof NavigationEnd).subscribe(val => { // here your code... })
Note: I have not tried this
Upvotes: 15