Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 *ngIf not reevaluation on model change

I have a navbar with 2 buttons. I wish to only show the button for the other page and disable the button for the current page.

On opening the settings page, the settings button is hidden. When I click the profile button, it doesn't disable and settings button doesn't appear.

Here's the component class code:

export class SettingsComponent implements OnInit {
   isSettingsProfile = false;
   isSettingsHome = false;
   
   ngOnInit() {
       this.isSettingsHome = true;
       this.isSettingsProfile = false;
   }
   
   OnNavBarClick(button: string) {
       if (button = "settings") {
           console.log ('setting home true/ profile false')
           this.isSettingsHome = true;
           this.isSettingsProfile = false;
       }
       else if (button = "profiles") {
           console.log ('setting home false/ profile true')
           this.isSettingsProfile = true;
           this.isSettingsHome = false;
       }
       
   }

And the navbar html:

        <ul class="nav navbar-nav navbar-right">
            <li> <a [routerLink]="['/home']" href="#">Home</a></li>
            <li *ngIf="!isSettingsHome" class="active"><a [routerLink]="['/settings']" href="#" (click)="OnNavBarClick('settings')">Settings</a></li>
            <li *ngIf="!isSettingsProfile"><a [routerLink]="['/settings/profile']" href="#" (click)="OnNavBarClick('profile')">Profile</a></li>
        </ul>

Any suggestions?

like image 758
John Baird Avatar asked Sep 03 '25 04:09

John Baird


1 Answers

I had this issue when implementing a breadcrumb component and have applied the solution proposed in this SO answer. I had to change to

import { ChangeDetectorRef } from '@angular/core';

because I use angular4 and then call

detectChanges()

at the end of your function OnNavBarClick()

like image 123
Loic T Avatar answered Sep 05 '25 01:09

Loic T