1

Problem: Calling multiple times when using angular directive. My transaction results are not correct. Multiple entries are entered on the Console screen.

I want to: Let the function execute only once.

Example code written

in HTML page

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

in .ts Page

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

Result:

,

2 2 2 2

I did a very simple example on the stackbilitz website.

Here is the link; StackBlitz Link

Is this an angular bug? Or is there something different I haven't considered?

Thank you in advance for all your answers.

Burak Odabaş
  • 347
  • 2
  • 8

2 Answers2

2

This is happening since you've called a function/method(TEST) in one of the data-binding syntaxes(*ngIf).

So whenever Angular performs Change Detection, your function will get called.

Change Detection is quite straightforward when it comes to variables. But it's different for functions. You see, the only way to check if the value of a function has changed is by calling it. That's why it is being called over and over again.

I've answered a few questions similar to this one here on StackOverflow. You might want to have a look at this answer for more information on all these scenarios related to performance.

You might also want to have a look at this talk by Tanner Edwards from NgConf 2018.

Hope this helps. :)

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
  • thanks, NgConf Video link is very good. I think that use pipe for solution – Burak Odabaş Oct 04 '19 at 14:31
  • @BurakOdabaş, the underlying fact would still be that if you use a method call in one of the data-binding syntaxes, you'd end up seeing that method called quite a lot of times eventually costing performance. – SiddAjmera Oct 04 '19 at 14:39
0

Because your function is in an *ngIf it will be called every change detection cycle (which happens a lot).

I try to follow this pattern:

First, reference a value from your component.ts file.

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

Second, only call this method when you need to update / change the value.

public testValue: number;

public setTest(number) {
  console.log (number);
  this.testValue= number;
}
Damian C
  • 2,111
  • 2
  • 15
  • 17