Monday, 26 November 2018

Angular ngAfterViewInit being called after every changeDetection

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.



from Angular ngAfterViewInit being called after every changeDetection

No comments:

Post a Comment