Ticker

6/recent/ticker-posts

How to get route URL in angular

 How to get route URL in angular




http://localhost:4200/hero?name=johndoe#highlights

then how can i get full URL or in segment?

If you want to route URL in string then use it: this.router.url (without window origin)

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

  import { Router, ActivatedRoute } from '@angular/router';


  @Component({

    selector: 'app-hero',

    templateUrl: './hero.component.html',

    styleUrls: ['./hero.component.css']

  })

  export class HeroComponent implements OnInit {

    constructor(private router: Router,  private activeRoute: ActivatedRoute) {       

      console.log('Get Router URL:', this.router.url);      

    }

    ngOnInit(): void {

    }

  }

// Output Log: 

Get Router URL: /hero?name=johndoe#highlights

If you want to route URL in segment then use: this.activeRoute.snapshot

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

 import { Router, ActivatedRoute } from '@angular/router';


  @Component({

    selector: 'app-hero',

    templateUrl: './hero.component.html',

    styleUrls: ['./hero.component.css']

  })

  export class HeroComponent implements OnInit {

    constructor(private router: Router,  private activeRoute: ActivatedRoute) { 

      this.activeRoute.queryParams.subscribe((qp) => {

        console.log('ActivatedRouteSnapshot:', this.activeRoute.snapshot);

      });

    }

    ngOnInit(): void {

    }

  }


Browser Output: