htmlangularrenderingangular2-templateconsole.log

How many times does Angular 2 render a single page before showing it?


I'm using Angular 2 for my project. I have a simple div in my template which calls a function in my .ts file that outputs a simple text like this:

<div>{{ test() }}</div>

test(): void {
    console.log("Test text");
}

When I load a page I get the same output many times like this:

Test text
Test text
Test text
Test text
Test text

Does that mean that Angular 2 renders the template many times before it actually shows it and consequently calls function every time?


Solution

  • Angular renders the AppComponent and it's child components exactly once, except when you add remove parts of the DOM, then these added parts will be rendered again.

    What you experience is Angulars change detection which runs quite frequently. See also Why event triggers ChangeDetection even if OnPush strategy is ON?.

    It is usually a bad idea to use functions in value bindings because such functions will be called every time Angular runs change detection.

    Prefer to assign the value to a property and bind to this property instead.

    <div>{{ testVal }}</div>
    
    ngOnInit() {
      this.testVal = this.test();
    }
    
    private test(): string {
        console.log("Test text");
        return 'some string';
    }