[javascript] Get current url in Angular

How can I get the current url in Angular 4? I've searched the web for it a lot, but am unable to find solution.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Router } from '@angular/Router';

import { AppComponent } from './app.component';
import { TestComponent } from './test/test.component';
import { OtherComponent } from './other/other.component';
import { UnitComponent } from './unit/unit.component';

@NgModule ({
  declarations: [
    AppComponent,
    TestComponent,
    OtherComponent,
    UnitComponent
  ],

  imports: [
    BrowserModule,
    RouterModule.forRoot([
        {
            path: 'test',
            component: TestComponent
        },
        {
            path: 'unit',
            component: UnitComponent
        },
        {
            path: 'other',
            component: OtherComponent
        }
    ]),
  ],

  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

app.component.html

<!-- The content below is only a placeholder and can be replaced -->
<div>
    <h1>Welcome to {{title}}!!</h1>

    <ul>
        <li>
            <a routerLink="/test">Test</a>
        </li>
        <li>
             <a routerLink="/unit">Unit</a>  
        </li>
        <li>
            <a routerLink="/other">Other</a>
        </li>
    </ul>
</div>
<br/>
<router-outlet></router-outlet>

app.component.ts

import { Component} from '@angular/core';

@Component ({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent{
    title = 'Angular JS 4';
    arr = ['abcd','xyz','pqrs'];
}

other.component.ts

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

@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) {}

    ngOnInit() {
        this.href = this.router.url;
        console.log(this.router.url);
    }
}

test.component.ts

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})

export class TestComponent implements OnInit {
    route: string;
    currentURL='';

    constructor() { 
        this.currentURL = window.location.href; 
    }

    ngOnInit() { }
}

Right now I am getting console issue after clicking on other link

ERROR Error: Uncaught (in promise): Error: No provider for Router!

This question is related to javascript angular typescript url-routing

The answer is


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);
        }
    }

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to url-routing

Get current url in Angular Vue.js redirection to another page AngularJS dynamic routing AngularJS - Animate ng-view transitions Using routes in Express-js RegEx to match stuff between parentheses Routing HTTP Error 404.0 0x80070002 Getting full URL of action in ASP.NET MVC