Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ngAfterViewInit being called after every changeDetection

Tags:

angular

From the angular docs for ngAfterViewInit

ngAfterViewInit()

Respond after Angular initializes the component's views and child views.

Called once after the first ngAfterContentChecked().

A component-only hook.

I have a component C which is nested inside component T

Component C implements the following hook.

ngAfterViewInit(): void {
        console.log("afterViewInit");
        debugger;
    }

Component T is a table - for which a change detection will occur whenever the user clicks a cell.

Component C can be found in a table cell.

Whenever I click the cell I can see afterViewInit logged in the console.

And my stack trace is as follow :

DynamicComponentWrapper.ngAfterViewInit (dynamic-component-wrapper.ts:72) View_TableComponent18.detectChangesInternal (/TableModule/TableComponent/component.ngfactory.js:904) AppView.detectChanges (view.js:425) DebugAppView.detectChanges (view.js:620) ViewContainer.detectChangesInNestedViews (view_container.js:67) View_TableComponent17.detectChangesInternal (/TableModule/TableComponent/component.ngfactory.js:962) AppView.detectChanges (view.js:425) DebugAppView.detectChanges (view.js:620) ViewContainer.detectChangesInNestedViews (view_container.js:67) View_TableComponent15.detectChangesInternal (/TableModule/TableComponent/component.ngfactory.js:1043) AppView.detectChanges (view.js:425)

Question

What is causing the ngAfterViewInit to be called on parent changes? Is the component being re-rendered - i.e - removed from the DOM and replaced?

And how do I prevent this? - i.e - how do I ensure ngAfterViewInit is only called once

Update: After changing both Component C and Component T to use ChangeDetectionStrategy.OnPush afterViewInit is still being called on any change.

like image 666
Daniel Cooke Avatar asked May 22 '17 09:05

Daniel Cooke


1 Answers

This might be due to some external directives used with child-components with which values from your mentioned component are also bound.

Related post:

Angular 7: ChangeDetectorRef detectChanges() causes infinite loop when called from inside a subscription

like image 176
Ravinder Payal Avatar answered Oct 15 '22 00:10

Ravinder Payal