Why does the *ngIf directive in Angular 2 always get executed when a function is used?

I'm working on developing an application using Angular 2 and implementing an auth service. Here is a snippet of my HTML template:

<header>
    <div *ngIf="isLogin()"><a href="">profile</a></div>
    <div *ngIf="!isLogin()"><a href="">register</a></div>
    <div *ngIf="!isLogin()"><a href="">signin</a></div>
    </header>

**Here is my class:** 

@Component({
    selector: 'main-menu',
    templateUrl: '/client/tmpl/menu.html',
    directives: [ROUTER_DIRECTIVES]
})
export class Menu extends Ext {

    public items: any;

    constructor(private _util: UtilService, private _user: UserService) {
        super();


    }

    public isLogin() {

        console.log("test");  <==== my problem occurs here
        return this._user.authorized();

    }


}

My functions seem to be executing continuously, especially when using a function inside *ngif. This raises concerns about resource consumption. Is this a potential issue that I should address?

Answer №1

Whenever Angular's change detection process is executed, it goes through all bindings to determine if the view should be updated.

It is not recommended to use functions in bindings. Instead, store the value in a property of your component class and bind to that property, or utilize observables along with the | async pipe to inform Angular about any changes.

Another approach is to employ ChangeDetectionStrategy.OnPush, which triggers Angular change detection only when there is a change in an input value.

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

YUI3 Searching with Selectors

I'm encountering an issue with selecting a single checkbox object in YUI3 based on its unique value attribute. In a table, there are multiple checkboxes with assigned unique keys to their value attributes. What should be the correct selector in YUI3 t ...

Adjust the scroll speed of the mouse

Is there a way to make my ReactJS application scroll to screen height with each mouse scroll? And if not, how can I manually set the scroll step for the mouse? Alternatively, I'm looking for a solution to detect the user's mouse step regardless o ...

I am looking to connect PubNub with Zendesk

Can Zendesk be integrated with PubNub? I am looking to set up a PubNub channel for each Zendesk ticket, and whenever I reply to a ticket with a message, I want to send a PubNub API request to store that message on the PubNub server. Essentially, I am see ...

Tips for creating a Bitbucket pipeline to deploy an Angular Universal application

I'm currently working on deploying my Angular universal app on a server using Bitbucket pipelines. The scripts I've written in bitbucket-pipelines.yml are as follows: pipelines: default: - step: name: Build app caches: ...

Creating a Component and Programmatically Returning a Value in Vue.js: A Step-by-Step Guide

Could you assist me in solving my issue? I am looking to develop a customized plugin for my project so that my team and I can easily implement an alert component without having to design the dialog box repeatedly on every page and vuejs file. My objective ...

Code for jQuery is found in a separate file

Previously, all of my jQuery code was written in the main file. Now, I am attempting to move it to another js-file. However, I am encountering an issue where it is not working correctly. FireBug displays the following error: $ is not defined $(document).r ...

You cannot click on the submit button within a form located in the datatable

While using a datatable with a form placed in one of the rows, users may experience an issue where the submit button does not work as expected. This could be due to conflicting code within the datatable files. Upon inspecting the vendor.js file containing ...

Automated Validation Grouping in Angular Reactive Forms Based on Control Properties

After implementing the following code block, I am uncertain if this is the correct behavior: this.formGroup = this.fb.group({ name: this.fb.group({ firstName: ['', Validators.required], lastName: ['', Validators.required] ...

Monitoring a location within a grid using AngularJS

I have a question: How can I track the position within a 10x10 grid in AngularJS and update it using arrow keys? Initially, I considered implementing this functionality in a directive with the following code: angular.module('mymodule').directiv ...

JavaScript used for making an AJAX request

Currently, I am attempting to master the art of making an AJAX call using plain JavaScript with the goal of stepping away from JQuery for a specific project. However, I seem to be encountering a roadblock when it comes to xmlhttp.onreadystatechange. If a ...

Dealing with jsonp in a rails 3 controller

I need my controller action to be able to handle jsonp requests triggered by jquery's $.getJSON method. Inside my controller action, I have the following respond_to block: respond_to do |format| format.html { render json: {:items_by_tag => @tagg ...

Why does passing a number from HTML to a JS function result in it becoming "undefined" in JS?

Below you will find a snippet of PHP and HTML: <?php $rowCountInDataTable=600; ?> ... <button onclick="<?php echo "showNextRows($rowCountInDataTable)"; ?>"></button>; Also included is some JS code: function showNextRows(totalRowC ...

The callback has already been invoked

While attempting to utilize the list.forEach method within async.waterfall in node.js, I encountered an error stating: if (fn === null) throw new Error("Callback was already called."); Error: Callback was already called. The goal is to make modification ...

Retrieving the dimensions of a concealed element

I am facing a minor issue and I need some assistance in figuring out what I might be missing here. Here is my html code: <div class="drop-down-menu"> <div class="innerdrop-down-menu"> <div id="first-tab-cont"> <ul id=" ...

Transmitting a JSON file to a remote server

I'm currently developing a game in p5.js and I'm looking for a way to allow players to save their game data. I've tried using saveJSON() in p5.js, but it only downloads the relevant data which isn't very helpful in this situation. I al ...

Tips for attaching the Bootstrap 5 dropdown menu to a particular element, especially when the dropdown element is contained within another element that has an overflow property set to hidden

I am utilizing the Bootstrap 5 dropdown menu within an owl-carousel. However, the dropdown is getting clipped because the outer div has an 'overflow:hidden' style in the owl-carousel. https://i.sstatic.net/YD9l2.jpg For the complete code snippe ...

The Javascript regex allows for the presence of positive and negative numbers, with the option of a single minus symbol

oninput="this.value = this.value.replace(/[^-0-9.]/g, '') This code snippet is utilized in my current project. However, there seems to be an issue where the input can contain more than one minus sign, as shown here: ---23 To address this p ...

What about combining a fat arrow function with a nested decorator?

Trying to implement a fat arrow function with a nestjs decorator in a controller. Can it be done in the following way : @Controller() export class AppController { @Get() findAll = (): string => 'This is coming from a fat arrow !'; } Wh ...

Receiving JSON using Javascript and vue.js

When attempting to fetch json data in my vue.js application, I use the following code: new Vue({ el: 'body', data:{ role: '', company: '', list:[], ...

Execute JavaScript after authentication instead of forwarding the user to another page

Short version: How can we efficiently handle a second AJAX call after an ASP.NET Membership Authentication response? Long version: Let's say we have a web-based Paint program created using ASP.NET MVC. A user is painting a picture when suddenly their ...