John David
John David

Reputation: 408

Angular 6 template doesn't update when variable changes

I have a menu object that will end up displaying a menu on the template. One of the menu objects properties is set by a variable that gets changed during the ngOnInit(). At that point, the template is already created I believe, so the menu never updates.

We want the MemberProfile link to display the user ID and not the 'undefined' that it is initialized with.

Check out the stack blitz link.

It's pretty straight forward I know I'm missing something simple.

When you open the menu, I'm printing out the Link Label and the Link URL. The second link should be Admin/MemberProfile/45 and not Admin/MemberProfile/undefined

https://stackblitz.com/edit/angular-ivy-yu9hty

Upvotes: 1

Views: 4736

Answers (2)

Ashutosh Pandey
Ashutosh Pandey

Reputation: 197

First, you need to understand how template/html rendering in Angular works.

As in your case, since you are rendering your menu link list from an array, menu.admin. Angular will not re-render the *ngFor block, until it detects changes in the menu.admin array. So, you just need to update that array.

Now, what you can do is something like this,

public ngOnInit() {
   this.userId = 45;

   this.menu.admin[this.menu.admin.length - 1].link = '/Admin/MemberProfile/' + this.userId
}

For more info please refer to Angular lifecycle hooks.

Upvotes: 2

mbojko
mbojko

Reputation: 14689

When the property menu is declared and assigned a value, this expression

'/Admin/MemberProfile/' + this.userId

is evaluated, using the then-current value of userId. When you do

this.userId = 45;

the value of menu isn't computed again.

There are several possible solutions. Put the menu layout in the template, instead of the TS (and use {{ userId }} there), use RxJS to update the thing dynamically, or simply imperatively recalculate the value of menu when changing userId (the most crude solution, and requiring the least amount of writing on my part), shown here:

https://stackblitz.com/edit/angular-ivy-qpnaqz?file=src/app/app.component.ts

Player's choice.

Upvotes: 1

Related Questions