ngOnChanges fires nonstop and makes application not to repond

1.4k Views Asked by At

I built a component with the name of "gw-responsive-tabs" that has an input with variable (navLinks) which is an Array of the tabs I want to display. When I deliver the input data from the html like that:

<gw-responsive-tabs
  [navLinks]="[{ label: 'PENDING', path: '/mentoring/manage/pending' },
  { label: 'CURRENT', path: '/mentoring/manage/pending' }]">
</gw-responsive-tabs>

Then everything works as expected and I can see 2 tabs.

If I change it and send the same Data using a getter or a function than the ngOnChanges of the gw-responsive-tabs component fires nonstop with very high frequency and from that point the chrome is not responding.

get mentoringTabs(): Array<any> {
  return [{ label: 'PENDING', path: '/mentoring/manage/pending' }, { label: 'CURRENT', path: '/mentoring/manage/pending' }];
}

and the html:

<gw-responsive-tabs [navLinks]="mentoringTabs"></gw-responsive-tabs>

Any ideas what can cause this phenomena?

1

There are 1 best solutions below

2
On BEST ANSWER

It's because of the change detection default strategy it's checked every sec or so And no matter what if the value of the return object is changed or not it re-render the template and because of that every time it's re rendering the html it's calling the get method which returns a new object everytime it's called and when the ngOnChanges compares it as the value is a new object now it runs in a loop.

here is the link to how change detection works https://angular-2-training-book.rangle.io/handout/change-detection/angular_1_vs_angular_2.html