Angular, confuse with console result

Viewed 45

I am very new to the angular. I'm confused with the console output of a angular app. First, see what I have did so far!

app.component.ts

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

@Component({
  selector: 'app-root',
  template: `
                {{getCourse()}}
            `,
   styleUrls: ['./app.component.css']
})
export class AppComponent {
    code = ['C++', "Python", "JAVA", 'ReactJS', "Angular"];
    getCourse()
    {
        for(let i = 0 ; i < (this.code).length ; i++)
        {
            console.log(this.code[i]);
        }
    }
}

Here, the AppComponent has one array code and one method getCourse(). I used inline template and data bind with getCourse() and this method iterate over the array and print on console. Here, is my console output. enter image description here See, here the same output repeated 4 times, not 1 time. Why? I wrote the logic to iterate the loop for one time.

1 Answers

Short answer - because of change detection. Your template rerenders (and do your getCourse() method) after any event on component or it descendants happened.

If you want to control changedetection maualy you have to set

@Component({
    ....
    changeDetection: ChangeDetectionStrategy.OnPush,
    ...
})

Add ChangeDetectorRef in your constructor, and trigger this._changeDetectorRef.markForCheck(); when you need rerender.

Also there some rules when change detection triggered byitself in case of OnPush strategy, for example on change Input value.

see for more info about change detection

https://blog.angular-university.io/how-does-angular-2-change-detection-really-work/

https://indepth.dev/everything-you-need-to-know-about-change-detection-in-angular/

Related