0

My app.component.html:

{{bla()}}

My app.component.ts:

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

@Component({
    selector: 'idr-app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterViewInit {
    constructor() {}
    ngAfterViewInit() {}

    bla(){
        console.log(77777);
    }
}

My app.module.ts:

import {BrowserModule} from '@angular/platform-browser';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
      BrowserModule,


     BrowserAnimationsModule,
    ],
    providers: [

    ],
    bootstrap: [AppComponent],
})
export class AppModule {
}

In console I see this situation:

app.component.ts:13 77777
app.component.ts:13 77777
core.js:3688 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
app.component.ts:13 77777
app.component.ts:13 77777

And if I use something like that {{bla()}} in child component, 77777 shows much more times

So someone knows why it redraws several times?

Olga Matosova
  • 136
  • 1
  • 1
  • 10
  • 2
    Possible duplicate of [function gets called several times](https://stackoverflow.com/questions/45207357/function-gets-called-several-times) – ConnorsFan Oct 12 '18 at 15:04

1 Answers1

2

This is due to Angular's default change detection strategy. If you change the strategy to onPush, you'll see the function is only executed once.

Here's a StackBlitz example: https://stackblitz.com/edit/angular-dfhfs7?file=src%2Fapp%2Fapp.component.ts

If you comment out the change detection, or set it to default, you'll see the console statement multiple times. If you set it to onPush, you'll only see the log statement once.

Here's an article that might help: https://netbasal.com/a-comprehensive-guide-to-angular-onpush-change-detection-strategy-5bac493074a4

Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144
  • So, will leaving the default change detection strategy be an issue? Because, I have some log that I see, which appear about 50 times in the console. This practically means that the statement is being executed about 50 times isn't it? Won't that be a performance hit? – Romeo Sierra Jan 21 '20 at 09:10
  • 1
    @RomeoSierra It can be, depending on the number of components present and other factors. I typically always disable the default change detection. – Brandon Taylor Jan 21 '20 at 13:41
  • I see. Thanks for the useful info @Brandon! :) – Romeo Sierra Jan 22 '20 at 05:16