Home > Blockchain >  Why the angular binding run 4 times?
Why the angular binding run 4 times?

Time:10-04

app.component.ts

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular '   VERSION.major;

  str = () => {
    console.log('123123');
  };
}

app.component.html

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>

<p>{{str()}}</p>

console.log

when I reload the browser and check the log. Angular relog 4 times. If you know why this happened, please let me know.

link stackblitz: https://stackblitz.com/edit/angular-ivy-zqjr2d?file=src/app/app.component.ts

CodePudding user response:

It is because you are calling a method in template, and angular doesn't know what that method could return, so it have to call it during every change detection cycle. In dev mode angular perform every change detection twice, plus when you load a component it have to render template then check it for changes.

load template check for whether template is correct = 2 cycles.

dev mode each cycle twice. so it becomes 2x2 = 4.

CodePudding user response:

By default, the component tree will be re-check/rendered every couple of seconds.
This behavior is due to how Angular evaluates the DOM (take a look at Angular lifecycle).

A way to improve it, is using ChangeDectionStrategy in the Component Object with the OnPush option, as it will be only checked once and when is explicitly invoked.

This article may help you as well=)

  • Related