6

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.

Daniel Cooke
  • 1,426
  • 12
  • 22
  • 1
    This is caused from the Angular change detection strategy. It is checking your whole component if an update has been made. You could try changing the detecting strategy, but that depends on how your made the bindings between your components. The best way to do that is by using clear Inputs / Outputs with dumb / smart components. If you depend on a router-outlet and can't use the Inputs / Outputs, you should be able to what you want without `ngAfterViewInit` and use a service to manage your data. – Alex Beugnet May 22 '17 at 10:01
  • @AlexBeugnet I experimented with `ChangeDetectionStrategy.OnPush` to no avail - change detection is still triggered when no inputs have changed. – Daniel Cooke May 22 '17 at 10:03

1 Answers1

1

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

Ravinder Payal
  • 2,884
  • 31
  • 40