Property referencing for change detection is a valuable technique

I'm struggling to update my template when changing a boolean property that is referenced in another array property. I expected the changes to reflect in my template, but they are not showing up.

Upon initial load, everything appears in its initial state (false: Login is visible and Logout is hidden). However, when the isLogged boolean changes, the navigation does not update to display the correct item.

I suspect this issue lies in how Angular handles change detection on objects and arrays, but I'm uncertain.

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  public isLogged: boolean = false;

  public navigation: INav = {
    links: [
      {
        text: 'Login'
        hidden: !this.isLogged
      },
      {
        text: 'Logout'
        hidden: this.isLogged
      }
    ]
  }

  public ngOnInit(): void {
    // Triggered whenever the login state changes
    this.authService.loginState().subscribe(state => {
      this.isLogged = state;
    });
  }

}
<third-party-nav [model]="navigation"></third-party-nav>

Answer №1

The issue at hand does not pertain to Angular's change detection system. The problem within your code lies in the fact that you're only setting the navigation once upon component creation, resulting in the variable isLogged being false. Instead, you should update it when the loginState changes. This can be achieved by leveraging observables/rxjs:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {


  public navigation: Observable<INav>;

  public ngOnInit(): void {
    // Updating the navigation object when the login state changes
    this.navigation = this.authService.loginState().map(s => ({
      links: [
        {
          text: 'Login',
          hidden: !s
        },
        {
          text: 'Logout',
          hidden: s
        }
      ]
    }));
  }
}

Subsequently, in your HTML, utilize the async pipe to manage the observable

<third-party-nav [model]="navigation | async"></third-party-nav>

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

Logging to the console using an If/Else statement, with the Else block containing code that

I'm encountering a peculiar issue with my If statement. I'm modifying the state (true/false) of an object based on onMouseEnter and onMouseLeave. I can execute the code when it's true, but if I include any code in the else statement, it ma ...

What is the best way to convert a state variable into a string in this scenario?

I have encountered an issue while using the NPM package react-date-countdown-timer. The countdown timer in this package requires a specific format for implementation: <DateCountdown dateTo='January 01, 2023 00:00:00 GMT+03:00' callback={()=> ...

Different ways to send data from JavaScript to Python using the 'POST' method

I have this specific section of code from my GAE application that utilizes webapp2 framework to receive data from a form through the post method. class RenderMarksheet(webapp2.RequestHandler): def post(self): regno = self.request.get('content ...

Issue with draggable div containing gmap not functioning on mobile browsers

Is it possible to make a specific div draggable without dragging the content inside, such as a gmap widget? I have tried implementing this functionality in my code and it works on a computer browser but not on a mobile browser. Here is the simplified versi ...

Tracking the progress bar as files are being uploaded via AJAX using HTML5

Currently, I have a progress bar that increments based on the number of files and their sizes. I am looking to implement an overall progress bar to display while uploading files to the server using AJAX and HTML5. Each file is uploaded individually to th ...

Get a CSV file through EmberJs

I have been experimenting with various function calls, but I am unable to figure out how to initiate a CSV download in EmberJs. Below is the most recent code I have tried: let endpoint = '/api/foo/'; let options = { url: endpoint, type: ...

How to retrieve the value of a variable accessible to all users in Angular?

In my code, I am working with a service variable called Users. Service: Users:BehaviorSubject<Array<any>> = new BehaviorSubject([]); I am updating the values in the component using this code: this.Service.Users.next([...this.Service.User ...

BroccoliMergeTrees function encountered an unexpected data type while attempting to merge trees: TreeMerger (lint) was expecting a Broccoli node, but received an [object

Since switching to Ubuntu 18.04, I've been trying to set up my Ember development environment but have encountered an issue. While my ember project works fine on Windows, I'm getting the error "BroccoliMergeTrees (TreeMerger (lint)): Expected Broc ...

What is the best way to ensure only one item is being selected at a time?

In the initial state, I want 'ALL' to be automatically selected. Clicking on another item should change the classes so that only 'this' has the class and the others do not. However, I am facing an issue where 'ALL' cannot be r ...

What could be causing my closing tag to abruptly end the section tag?

I encountered an issue that says the 'section' is closed by another tag. Upon reviewing my HTML code, everything appears to be correct. <ng-container *ngIf="display$ | async as display"> <section [class.open]="display ...

Can you tell me how to add a custom CSS class to a cell in ag-grid using Angular?

I am facing a challenge with applying CSS to cells in ag-grid in Angular based on specific logic. I have assigned an object to the grid, where one of the fields contains a value for Object.hours and I need to apply styling based on the Object.status proper ...

The search function in Select2 is not displaying the desired result

I'm encountering an issue with the search functionality when it uses Ajax to load data from a JSON file. For example, if I search for Yemen, the record for Yemen does not get selected or highlighted properly. Here is the complete source code - could ...

Is there an advantage to pre-compiling jade templates for production in an express environment?

Is it advantageous to have a middleware that pre-compiles all .jade views for production use, or does this happen automatically when NODE_ENV is set to 'production'? I am investigating ways to accelerate jade rendering for production purposes. ...

Is there a way to add another item to a repeated DOM element without having to modify the ng-repeat scope?

I am working with a list of items using ng-repeat <div layout="column" class="md-whiteframe-1dp" ng-repeat="item in child.items track by item._id" id={{item._id}}child> </div> I am looking to add an additional DOM ele ...

The login function in Nativescript Vue successfully returns a true value

Hello, I am currently using a function that is quite similar to this one with some minor tweaks here. However, I have encountered an issue when trying to log in to my REST API. Even if I input the incorrect username or password, it still authenticates me ...

The absence of HTML and CSS is preventing the inclusion of an Ajax image viewer, back button, and

Currently, I am experimenting with jQuery and JavaScript to create an ajax overlay image viewer for a PHP website. After adding this code snippet at the end of the 'gallery page', I can successfully open the viewer and navigate using the next and ...

What is the process for exporting an NPM module for use without specifying the package name?

I am looking for a way to export an NPM module so that it can be used without specifying the package name. Traditionally, modules are exported like this: function hello(){ console.log("hello"); } module.exports.hello = hello; And then imported and ...

Refresh jQuery CSS for active button whenever a different button is clicked

I want to enhance a group of buttons using jQuery. I aim to make the active button visually stand out so that users can easily identify it. These buttons are being created through a PHP foreach loop, as shown below: foreach($result as $row){ echo "< ...

Confusion arises between Bootstrap button plugin and Vue checkbox click event

After incorporating bootstrap.min.js into my Vue app, I noticed that the checkboxes' @click event is no longer triggered. This issue specifically occurs when using bootstrap's button-group with data-toggle="buttons". If I remove bootstrap.min.js, ...

JEST: Troubleshooting why a test case within a function is not receiving input from the constructor

When writing test cases wrapped inside a class, I encountered an issue where the URL value was not being initialized due to dependencies in the beforeAll/beforeEach block. This resulted in the failure of the test case execution as the URL value was not acc ...