Get current url in Angular [duplicate]
With pure JavaScript:
console.log(window.location.href)
Using Angular:
this.router.url
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
template: 'The href is: {{href}}'
/*
Other component settings
*/
})
export class Component {
public href: string = "";
constructor(private router: Router) {}
ngOnInit() {
this.href = this.router.url;
console.log(this.router.url);
}
}
The plunkr is here: https://plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p=preview
You can make use of location service available in @angular/common and via this below code you can get the location or current URL
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
@Component({
selector: 'app-top-nav',
templateUrl: './top-nav.component.html',
styleUrls: ['./top-nav.component.scss']
})
export class TopNavComponent implements OnInit {
route: string;
constructor(location: Location, router: Router) {
router.events.subscribe((val) => {
if(location.path() != ''){
this.route = location.path();
} else {
this.route = 'Home'
}
});
}
ngOnInit() {
}
}
here is the reference link from where I have copied thing to get location for my project. https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts
other.component.ts
So final correct solution is :
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
/* 'router' it must be in small case */
@Component({
selector: 'app-other',
templateUrl: './other.component.html',
styleUrls: ['./other.component.css']
})
export class OtherComponent implements OnInit {
public href: string = "";
url: string = "asdf";
constructor(private router : Router) {} // make variable private so that it would be accessible through out the component
ngOnInit() {
this.href = this.router.url;
console.log(this.router.url);
}
}