2

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

That didn't work. I implemented with little modification this.pageTitle = this.router.events.pipe(map((event) => { return event instanceof NavigationEnd && event.url.includes('something') ? 'About US' : 'Default Title'; })); I am always getting the output as Default Title.
it works: stackblitz.com/edit/angular-scdiic, I have improved the Observable mapping but the idea remains same

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.