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
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
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
}
});
}
}
Try any of these from the native window object.
console.log('URL:' + window.location.href);
console.log('Path:' + window.location.pathname);
console.log('Host:' + window.location.host);
console.log('Hostname:' + window.location.hostname);
console.log('Origin:' + window.location.origin);
console.log('Port:' + window.location.port);
console.log('Search String:' + window.location.search);
NOTE: DO NOT USE THIS IN SERVER SIDE RENDERING
You can use Angular Location Service.
import { Location } from '@angular/common';
You can access the path using:
location.path();
If you want the complete URL, use LOCATION instance as follows :-
([Location][1])location.href = https://test-mydomain.com/#/securelogin?name=batman
& if you want relative URL, use ROUTER instance follow :-
this.router.url = securelogin?name=batman
Follow the complete snippet as follows based on angular 4:-
constructor( private router: Router) {
console.log(this.router.url);
/**
* securelogin?name=batman
*/
console.log(location.href);
/**
* https://test-mydomain.com/#/securelogin?name=batman
*/
}
I was about to answer this question but I have the same answer with BigBrother. This answer is for those who uses "#" on their URL as it only returns "/" on some router location code.
This is a sample code of one of my project:
this.router.events.subscribe((event) => {
if(event instanceof NavigationEnd) {
this.currentPage = event.url;
if ( event.url != '/admin') {
setTimeout(()=>{
this.modalRef = this.modalService.show(ModalSurveyComponent,this.config);
}, 3000);
}
}
});
So Pop up will only show if the current route is not "/admin"
import { RouterStateSnapshot } from '@angular/router';
constructor(private state: RouterStateSnapshot) {
console.log("Current Url Path", state);
}