如何知道用户是否离开我的组件路由在Angular 15中?

huangapple go评论64阅读模式
英文:

How to know if user left my component route in Angular 15?

问题

ngOnDestroy 在用户在应用程序的不同路由之间切换时不会触发。

是否有其他方法可以知道用户离开我的组件路由并销毁组件?

英文:

ngOnDestroy doesn't trigger when a user switches between different routes of the application.

Is there any other way to know if the user leaves my component route and destroy component then?

答案1

得分: 1

ngOnDestroy 在用户在应用程序的不同路由之间切换时不会触发。

这不是真的,当组件从 DOM 中移除时,ngOnDestroy() 会被调用,参见这个 Stackblitz

当路由被更改(点击其中一个按钮),ngOnDestroy() 会在被移除的组件上调用。

你可以通过获取对组件的引用并调用 .destroy() 来手动销毁组件,但这通常不推荐。

英文:

> ngOnDestroy doesn't trigger when a user switches between different routes of the application.

That's not true, ngOnDestroy() is called when the component is removed from DOM, see this Stackblitz.

When the route is changed (click one of the buttons), ngOnDestroy() is called on the component that is being removed.

You can manually destroy a component by getting the reference to it and calling .destroy() but that is generally not recommended.

huangapple
  • 本文由 发表于 2023年4月4日 15:02:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75926389.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定