-1

I am building the Breadcrumb(Home > Calendar) for my project. I want the Breadcrumb to be updated depending on the component I am in:

Home > Calendar

Home > Visit Us

For this I need the current path (which I have) and I need to use 'Observables' to get the changed path.

Q1) I need to use 'Observables' to get the changed path?

...this is where I am stuck!

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

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
 r:string;
  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
   // Got the current route, WORKS!
   this.r = this.route.url;
   // But, how do I use observables to get the changed path if user goes to a different page
   this.route.url.subscribe((url: string)=>{
    this.r = url;
   })
  }

}
<div class="container">
 <div class="row">
  <div class="col-sm-8">
   <h1>musem</h1>
   <h6>ONTARIO</h6>
  </div>
  <div class="col-sm-2">
   <button class="btn btn-lg">
    <i class="fas fa-envelope"></i> Edit
   </button>
  </div>
  <div class="col-sm-2">
   <button class="btn btn-lg">
    <i class="fas fa-map"></i> Find
   </button>
  </div>
 </div>

 <nav aria-label="breadcrumb">
  <ol class="breadcrumb bg-transparent">
      <li class="breadcrumb-item"><i class="fas fa-home"></i></li>
      <li class="breadcrumb-item active" aria-current="page">{{r}}</li>
    </ol>
 </nav>
 <hr>
</div>
M Masood
  • 167
  • 1
  • 10

2 Answers2

1

You should listen to the router events, and by using NavigationEnd event you can get the correct path by accessing evt.url which is the path of the changed route

import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
......
ngOnInit() {
    this.router.events.subscribe((evt: any) => {
      if (evt instanceof NavigationEnd) {
        console.log(evt.url) //path of the route
      }
    });
}
Nithya Rajan
  • 4,722
  • 19
  • 30
1

You should inject Router in your component where you want to listen for change and subscribe to router.events. I have linked a stackblitz demo below.

Demo: https://stackblitz.com/edit/angular-router-basic-example-tpucgr?file=app/app.component.ts

IMHO it would be better if you create a breadcrumb component in app.component.ts. Create a service for breadcrumb. Register the instance of breadcrumb component in this service, then inject this service in component where you want the breadcrumb to change and call method inside the service which in turns call the methods of breadcrumb component to update the breadcrumb.

Also see this answer

alt255
  • 3,396
  • 2
  • 14
  • 20