微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

每次changeDetection后调用Angular ngAfterViewInit

来自ngAfterViewInit的角度文档

ngAfterViewInit()

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

Called once after the first ngAfterContentChecked().

A component-only hook.

我有一个嵌套在组件T内的组件C.

组件C实现以下钩子.

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

组件T是一个表 – 只要用户单击一个单元格,就会对其进行更改检测.

组件C可以在表格单元格中找到.

每当我单击单元格时,我都会看到在控制台中登录后的ViewInit.

我的堆栈跟踪如下:

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)

是什么导致在父更改时调用ngAfterViewInit?组件是否被重新渲染 – 即从DOM中删除并替换?

我该如何防止这种情况? – 即 – 我如何确保只调用一次ngAfterViewInit

更新:
更改组件C和组件T以使用ChangeDetectionStrategy.OnPush后,仍然会在任何更改时调用afterViewInit.

解决方法

这可能是由于一些外部指令与子组件一起使用,您提到的组件中的值也会与其绑定.

相关文章

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐