Sarath
Sarath

Reputation: 376

How to bind routing events URL into HTML template in Angular

I have an angular component with in which i am trying to bind a public variable based on the router URL. The public variable is assigned a value inside subscribe method, so because of this the template is not updated on initial load.

  pageTitle: string;
  constructor(private router: Router) {}
  ngOnInit() {
    this.router.events.subscribe((event) => {
       if (event instanceof NavigationEnd) {
          if(event.url ==="something" {
             this.pageTitle ="About US"
            }
         }
  })
}

I am binding the pageTitle variable in the HTML file

<div class="title">{{pageTitle}}</div>

On refreshing the page, i am able to see the pageTitle, but on initial load the value is not shown.

Upvotes: 2

Views: 1117

Answers (1)

MarcinL
MarcinL

Reputation: 130

if your pageTitle changes you should try to make it observable and handle with async pipe to keep it up to date

Added Stackblitz implementation: https://stackblitz.com/edit/angular-scdiic

try something like this

    this.title = this.route.events.pipe(
      filter(event => event instanceof NavigationEnd),
      map((event: NavigationEnd) => event.url));
<div class="title">{{pageTitle | async}}</div>

also for better understanding read about how change detection works in Angular like here: https://auth0.com/blog/understanding-angular-2-change-detection/ for a good start

Upvotes: 2

Related Questions