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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.