Issue with triggering angular function multiple times in certain conditions

Issue: Experiencing difficulties with Angular directive as it is being called multiple times, resulting in incorrect transaction outcomes and multiple entries on the Console screen.

Desired Outcome: Ensure that the function executes only once.

Sample code snippet

within HTML page

<div *ngIf="TEST(0)"> </div>

within .ts Page

TEST(number) {
  console.log (number);
}

Outcome:

https://i.sstatic.net/WX11K.png

2 2 2 2

I have provided a simple example on the StackBlitz website.

Here is the link; StackBlitz Link

Could this be an angular bug? Or is there something I am missing?

Appreciate your insights in advance.

Answer №1

The reason for this recurring event is due to the invocation of a function/method (TEST) within one of the data-binding syntaxes (*ngIf).

Each time Angular conducts Change Detection, the function will be triggered.

Change Detection handles variables straightforwardly, but functions operate differently. The only way to determine if a function's value has changed is by executing it, hence the repetitive calls.

If you're interested in exploring similar topics, I've provided answers on StackOverflow before, like this one that delves into various scenarios affecting performance.

You may also find value in watching a presentation by Tanner Edwards from NgConf 2018.

I hope this sheds some light on the situation. :)

Answer №2

Because your function is contained within an *ngIf statement, it will be triggered during every change detection cycle.

I typically adhere to the following approach:

First, access a variable from your component.ts file.

<div *ngIf="testVariable"> </div> 

Secondly, only invoke this method when you need to update / modify the variable.

public testVariable: number;

public setTest(number) {
  console.log (number);
  this.testVariable = number;
}

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

Looking to display a single Angular component with varying data? I have a component in Angular that dynamically renders content based on the specific URL path

I have a component that dynamically renders data based on the URL '/lp/:pageId'. The :pageId parameter is used to fetch data from the server in the ngOnInit() lifecycle hook. ngOnInit(){ this.apiHelper.getData(this.route.snapshot.params.pageId) ...

Expanding and collapsing table rows in Angular 5 sequentially

I have been attempting to implement an angular table row expand/collapse feature, but I am having trouble getting it to work correctly. I tried using the following URLs for assistance, but they did not seem to solve the issue. Any guidance would be greatl ...

Strategies for updating JSON file content as data evolves

I am facing an issue with loading a json file that populates charts. The file is generated from external data sources and stored in the asset directory. Is there a method to automatically load the updated json file? I have attempted to include the code fo ...

The issue with Angular's mat-icon not displaying SVGs masked is currently being investigated

I have a collection of .svgs that I exported from Sketch (refer to the sample below). These icons are registered in the MatIconRegistry and displayed using the mat-icon component. However, I've observed issues with icons that utilize masks in Sketch ...

Binding textarea data in Angular is a powerful feature that allows

I am looking to display the content from a textarea on the page in real time, but I am struggling to get the line breaks to show up. Here is my current code snippet: app.component.html <div class="ui center aligned grid">{{Form.value.address}}< ...

What is the process for upgrading ag-Grid to newer versions?

In the past, I was using: "ag-grid": "^18.1.2", "ag-grid-angular": "^18.1.1" Version "^18.1.1" of "ag-grid-enterprise". However, as my license expired, I obtained new versions of the licenses. I then included: "@ag-grid-community/angular": "^22.1.1", ...

The autocomplete feature is not functioning properly when attempting to prefill form inputs with values from another component

After utilizing a service to transfer values from the first component to the second, I encountered an issue. When trying to fill out a form on the first component (url: localhost:4200) and submitting it, the redirection to url: localhost:4200/results where ...

The error message "Property 'list' is not found on type 'void' React - Material UI" indicates that the 'list' property is not recognized

Currently, I am facing an issue while working with Material UI and React Typescript. The error message I receive is "Property 'list' does not exist on type 'void'" when attempting to use makeStyles and createStyles to remove padding. It ...

Adding an icon to the contents of a specific column in Angular material

Struggling to figure out how to incorporate an icon into the data in the Status column using Angular material. Here is the markup of my page: <table mat-table [dataSource]="dataSource"> <ng-container *ngFor="let ...

Error message "NoSuchKey" encountered on CloudFront when accessing an Angular application

I recently developed an Angular application and successfully uploaded it to an S3 bucket. To make my website accessible, I deployed a CloudFront distribution. However, when trying to access a specific route on the website (such as /login), I encountered an ...

What is the process for implementing a unique Angular theme across all components?

I created a unique Angular theme called 'my-theme.scss' and added it to the angular.json file. While it works with most Angular Elements, I am facing issues getting it to apply to certain HTML Elements inside Angular Components. For example: < ...

Is it possible to use TypeScript or Angular to disable or remove arrow key navigation from a PrimeNG Table programmatically?

Is there a way to programmatically prevent left and right arrow key navigation in a PrimeNG Table with cell editing, without the need to modify the Table component source code? You can check out an example here: Angular Primeng Tableedit Demo code. I mana ...

Having difficulty transferring navigation props between screens using react-navigation

Within my ContactList component, I have utilized a map to render various items. Each item includes a thumbnail and the desired functionality is that upon clicking on the thumbnail, the user should be directed to a new screen referred to as UserDetailsScree ...

Encountering an Error in Angular with Jest: TypeError Unable to Access Property 'ngModule' from null

Challenge I have been trying to implement Jest testing for my Angular application. Following the guidelines provided by jest-preset-angular, I encountered an error when running tests with Bazel using this target: FAIL services/client/src/app/app.componen ...

Adding a ng-select field when a button is clicked

In my template, I am using ng2-select to allow users to select items. There is a button called "Add" that, when clicked, should display another select field with a list of different item categories. However, the current version of my code does not achieve ...

Bring JSON into Angular 7 application

For my Angular project, I've set up a localization service by importing JSON files. Following this recommended method, I updated my typings.d.ts as shown below: declare module "*.json" { const value: any; export default value; } Everything w ...

Generic Typescript Placeholder Design

Imagine you have the following data: const dataA = { name: "John", age: 25, attributes: {specificA: "hello", specificA2: 14, nonspecific:"Well"}, } const dataB = { name: "Lisa", age: 38, attributes: {spe ...

How can we restrict a user from moving away from the current tab in Angular?

I am looking for a solution to restrict users from switching tabs or opening new ones during an exam on our application for security purposes. What recommendations do you have to accomplish this? ...

Node path response not being properly configured

Just diving into the world of node and typescript and could use a bit of guidance. Currently utilizing node/express/postres as backend and leveraging https://github.com/typeorm/typeorm as an orm, which offers a function to open a connection structured as f ...

Exploring the keyof operator in Typescript for object types

Is there a way to extract keys of type A and transfer them to type B? Even though I anticipate type B to be "x", it seems to also include "undefined". Why does the keyof operator incorporate undefined in the resulting type? It's perplexing. I kn ...