Angular 2 does not automatically re-evaluate *ngIf on model change

I am working on a navigation bar that consists of 2 buttons. My goal is to display only the button for the other page and disable the button for the current page.

Currently, when I navigate to the settings page, the settings button is hidden. However, when I click on the profile button, the settings button does not disable as expected.

Below is the code for the component class:

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;
       }
       
   }

Here is the HTML for the navbar:

        <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 tips or suggestions on how to fix this issue?

Answer №1

While working on incorporating a breadcrumb component, I encountered an issue that was resolved by following the advice provided in this helpful response on Stack Overflow. I made a necessary adjustment by switching to

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

due to the fact that I am using Angular 4. After that, don't forget to add

detectChanges()

to the end of your OnNavBarClick() function.

Answer №2

A duplicate " is present in the code snippet

<li *ngIf="!isSettingsHome"" class

Answer №3

The situation here is a bit unclear to me, and without more detail about your router setup, it's hard to give an accurate diagnosis. However, it seems likely that Gunter's suggestion about the navigation causing a component reload, thus resetting it to its original state, could be correct. To address this issue, I would recommend the following restructuring approach:

Start by incorporating the routerLinkActive directive into your router links, and assign the class as "hide-link" (or any other preferred name)

 <li><a [routerLink]="['/settings']" routerLinkActive="hide-link">Settings</a></li>

Next, create a basic CSS class to hide the link

.hide-link { display: none; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transform Observable RxJS into practical results

In a straightforward scenario, I have an upload action on the page that looks like this: onUpload$: Subject<SomeUpload> = new Subject<SomeUpload>(); uploadAction$: Observable<Action> = this.onUpload$.map(entity => this.someActionServi ...

Tips for hiding a sidebar by clicking away from it in JavaScript

My angular application for small devices has a working sidebar toggling feature, but I want the sidebar to close or hide when clicking anywhere on the page (i.e body). .component.html <nav class="sidebar sidebar-offcanvas active" id="sid ...

What steps are needed to integrate a Spring Boot application with Angular 2?

After incorporating Angular 2 into my Spring Boot application, I successfully deployed all of my files. However, the routing feature is not working as expected. Below is the file structure. This setup works smoothly with a Node.js server. https://i.sstati ...

Transforming .d.ts files into HTML documentation

I possess a TypeScript declaration file (.d.ts) carefully documenting each function of an API. Can this documentation be elegantly displayed on a website in HTML format? Is there a solution for converting a .d.ts into a visually appealing .html document? ...

Can the return value of a function be directly used as the variable type?

Imagine having the following function: let getData = () => { return { name: 'John', age: 2, isAsian: true } } Is there a way to specify a variable's type as the return type of getData, without assigning i ...

An issue was encountered in the node_modules folder while attempting to access the 'Exclude' name in the lodash collection file. The error message reads: (1783,24): error TS2304: Cannot

When attempting to execute the ng serve command, I encountered an error. See below for more details. ERROR in node_modules/@types/lodash/common/collection.d.ts(1783,24): error TS2304: Cannot find name 'Exclude'. ... (error list continued) .. ...

When retrieving data from MongoDB, an error occurs stating "Unable to read the property 'firstname' of null."

I've been working on retrieving user information from MongoDB and displaying it through HTML, but I keep encountering an error that says: "Cannot read property 'firstname' of null." For my backend service, I'm using Express and Node.js, ...

the quickest method to apply font-weight:bold; to the text within the component

Is there a way to apply font-weight: bold; only to the inner content of a component in a scss file while avoiding affecting the component tag itself? :host { font-weight: bold; } Although this code works, it also affects the component tag itself. What ...

Uploading images using the power of Angular and Node.js

I have been struggling with a persistent issue for quite some time now, and I have not been able to find a solution anywhere. My goal is to allow users to update their avatars on their profiles. However, every time I attempt to pass the file to my node ser ...

If I don't utilize dependency injection in Angular, it prompts me for arguments

Attempting to implement a service like this but encountering some issues translateService = new TranslateService(); An error message pops up stating that there are 9 missing arguments. However, when I modify it to look like this constructor(private trans ...

Angular's observable data fail to show on the screen

I am facing an issue with passing the data of an Observable fetched via an API request to a component variable for display. I have been trying but unable to make it work successfully. Any assistance would be greatly appreciated. Here is my code. Thank you. ...

Typescript error TS2717: All following property declarations should share the same data type

During development on my local host, the TypeScript build works perfectly fine. However, when transitioning to Docker with a Node image, I encounter a peculiar error during the build process: src/middlewares/auth.ts(16,13): error TS2717: Subsequent propert ...

What is the best way to access an optional field in Typescript without causing errors?

Is there a way to dereference an optional field from an interface in the following scenario? interface Sample { key1?: Array<Obj1> } interface Obj1 { a?: Obj2; } interface Obj2 { b?: string; } const a: Sample["key1"][number][" ...

How to generate a SAS token or URL for a blob in React?

Hey there! I'm working on a React app that's written in TypeScript. I need to retrieve the document name as a query parameter and then get the SAS URL of the document for additional processing. Do you have any suggestions on how I can accomplish ...

Transferring an Image from Angular 7 to Spring-boot

I've been attempting to transfer images from my Angular application to Spring Boot, but I'm encountering issues. When I send a POST request from Angular with the file, Spring Boot doesn't respond as expected. To investigate further, I tested ...

Exploring the world of Typescript and Angular Filter functionalities

I am looking to utilize one of my Angular Filters in my controller as a function. I came across a solution on this page: How to use a filter in a controler The last answer provided exactly what I needed, so I implemented it in my JS code: var MyFunc ...

Pass on only the necessary attributes to the component

I have a simple component that I want to include most, if not all, of the default HTML element props. My idea was to possibly extend React.HTMLAttributes<HTMLElement> and then spread them in the component's attributes. However, the props' ...

An error occurred: Unable to locate the file or assembly 'Interop.iTunesLib, Version=1.13.0.0, Culture=neutral, PublicKeyToken=null'

I've been attempting to connect to iTunes using C# programming language. The process involves creating a dll in C# and running it with TypeScript through the Overwolf API. Here's what I've done so far: Generated a .dll file I utilized the ...

Steps for transferring an uploaded .CSV file to a Web service

I'm exploring the process of sending a file uploaded from the UI (angular) to a .NET web service in order for it to parse a CSV file and create a list of objects. My current understanding of the logic flow is: File upload ---> Web Service (parse ...

What is the best way to display toastr messages in an Angular application?

Can you guide me on how to include toastr in an angular app? Currently, I am enrolled in the Angular Fundamentals course and trying to use toastr.success within my export class: handleThumbnailClick(eventName){ toastr.success(eventName) } But, I kee ...