I have a parent component and a child component. I know that change detection runs on events like HTTP request, setInterval
or setTimeOut
etc.
But here I don't have any of these events, and yet, when my parent component initially loads, the child component method calledChildCompo()
is called four times.
Why is the change detection executed four times on initial load when I don't have events such as HTTP requests or any intervals?
AppComponent (parent)
<app-change-det></app-change-det>
ChangeDetComponent.html (child)
{{ calledChildCompo() }}
ChangeDetComponent.ts (child)
@Component({
selector: 'app-change-det',
templateUrl: './change-det.component.html',
styleUrls: ['./change-det.component.scss']
})
export class ChangeDetComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
calledChildCompo() {
console.log('child compo is called');
}
}
Have a look at the below Demo with no child component or parent component Demo
What I have is simply
TS
HTML
If you look at the console You will see 4 logs with the word
TEST
but only 1 'init'. It simply a function working as expected, function reevaluates severally.It is important to note that this reevaluation may cause your application to become slow. it is a bad idea to include functions in the html. Functions reevaluate for any slight change
Explanation