I just found that I have created a new angular 7 project and I have created a method in the app.component.ts with the following code.
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'angular-test';
constructor() {}
prueba(){
console.log('Hello World!');
}
}
Then in the app.component.html I call the method, attached code.
app.component.html
{{prueba()}}
And this is the result, it takes it out more than 1 time and I don't understand the reason.
Project zip: https://www92.zippyshare.com/v/MHAEjb1p/file.html
This happens because you call the test() function on an expression like this:
This function will be called at least twice if you use expressions like that.
The reason is because Angular executes digest cycle until everything is updated (so it will be at least twice). In your case, it will run the first time to return the value and the second time to check for any changes left.
Calling a function that way is not good practice.
The reason that the console.log is executed several times is because of the changes in the angular stop. Here he explains it more in depth.
https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html
The way you are trying to execute that function is not correct.
If you want it to be executed as soon as you start the web, you must use the method
ngOnInit()
All the best
I would like to know what happens in the case that it is executed from the ngOninit but it continues to execute many times I have the response from a service I do not call my method {{function()}} but from the NgOnInit but it continues to load hundreds of times, locally only calls 1 time but on a server many times