我有这样一个场景;组件 A 转到 B ,当我返回 A 时, @viewChild 元素未定义。我尝试在 ngAfterViewInit、ngAfterContentInit 中访问它,但它总是未定义。这是我最后一次尝试:
@ContentChild('item', { static: false }) item: ItemComponent;
ngAfterContentInit() {
if (this.item) {
this.item.resetFilters();
}
后退按钮,导致 SPA 应用程序无法正常工作,因为上一屏幕的状态丢失,您可以使用以下代码触发组件的重新加载。
您可以将此代码放置在应用程序的根目录中,例如
app.component.ts
。
下面的代码不会刷新屏幕,而是重新加载组件。
import { HostListener } from '@angular/core';
constructor(private router: Router) {}
@HostListener('window:popstate', ['$event'])
onBackButton(event) {
this.router.navigateByUrl(`${window.location.pathname}`, {
skipLocationChange: true,
onSameUrlNavigation: 'reload',
});
}
您还可以按后退按钮刷新页面。
import { HostListener } from '@angular/core';
@HostListener('window:popstate', ['$event'])
onBackButton(event) {
location.reload()
}