So I need somehow check if I am on home page and do something and in other pages don't do that. Also that component imported on all of pages.
How can I detect on that component if I'm on home page???
Thanks
There are many ways by which you can get a current Route or URL in Angular. You can use the router service, location service or window object to get the path. You can also listen to changes to URL using the router event or URL change event of the location service.
Step 1: Import ActivatedRoute from Router module. import { ActivatedRoute } from '@angular/router'; Step 2: Inject ActivatedRoute in constructor. Now we have id in edit_quiz.
NavigationEndlinkAn event triggered when a navigation ends successfully. class NavigationEnd extends RouterEvent { constructor(id: number, url: string, urlAfterRedirects: string) type: EventType.
RouteStateSnapshot is an immutable data structure representing the state of the router at a particular moment in time. Any time a component is added or removed or parameter is updated, a new snapshot is created.
Try this,
import { Router } from '@angular/router';
export class MyComponent implements OnInit {
constructor(private router:Router) { ... }
ngOnInit() {
let currentUrl = this.router.url; /// this will give you current url
// your logic to know if its my home page.
}
}
Try it
import { Component } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({...})
export class MyComponent {
constructor(private router:Router) {
router.events.subscribe(event => {
if (event instanceof NavigationEnd ) {
console.log("current url",event.url); // event.url has current url
// your code will goes here
}
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With