Angular在页面上插入组件后,切换路由时无法移除旧组件。
创始人
2024-10-30 21:31:04
0次
  1. 在路由切换时手动移除旧的组件,可使用AfterViewInit生命周期钩子来实现。 示例代码:

import { Component, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, OnDestroy, AfterViewInit } from '@angular/core'; import { RouterOutlet, Router } from '@angular/router';

@Component({ selector: 'app-my-component', template: '' }) export class MyComponent implements OnDestroy, AfterViewInit { private childComponentRef: ComponentRef; @ViewChild('childContainer', { read: ViewContainerRef }) private childContainer: ViewContainerRef;

constructor( private componentFactoryResolver: ComponentFactoryResolver, private router: Router ) {}

ngAfterViewInit() { this.router.events.subscribe((event) => { if (event instanceof NavigationEnd) { this.childContainer.clear(); // 移除旧组件 const factory = this.componentFactoryResolver.resolveComponentFactory(NewComponent); const componentRef = this.childContainer.createComponent(factory); this.childComponentRef = componentRef; } }); }

ngOnDestroy() { if (this.childComponentRef) { this.childComponentRef.destroy(); } } }

  1. 使用路由守卫对旧路由或旧组件进行处理,然后再加载新组件。示例代码:

import { Router, NavigationEnd } from '@angular/router'; import { filter } from 'rxjs/operators';

constructor(private router: Router) { this.router.events.pipe( filter(event => event instanceof NavigationEnd) ).subscribe(event => { // 处理旧组件或旧路由 this.router.routeReuseStrategy.shouldReuseRoute = () => false; }); }

在app.module.ts中添加以下代码:

import { RouteReuseStrategy } from '@angular/router';

export class CustomReuseStrategy implements RouteReuseStrategy { shouldReuseRoute( future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot ): boolean { return future.routeConfig === curr.routeConfig; }

retrieve(
    route: ActivatedRouteSnapshot
): DetachedRouteHandle |

相关内容

热门资讯

分享认知透视!微乐三丁拐ai透... 分享认知透视!微乐三丁拐ai透视多功能插件,其实是真的有透视插件指引主打本地运行的 AI 黑科技工具...
实测发现开挂!锦州麻将ai开挂... AI 黑科技赛道又上新,这款智能处理工具堪称效率开挂,专门面向短视频创作者打造。它打通脚本撰写、AI...
揭秘攻略透视!皮皮四川麻将至尊... 揭秘攻略透视!皮皮四川麻将至尊版ai透视多功能插件,起初真的是有透视方法指南;近期一款 AI 黑科技...
每日必看推荐辅助!友友麻将ai... 每日必看推荐辅助!友友麻将ai辅助多功能插件,都是真的是有辅助技巧课程是一款可以让一直输的玩家,快速...
玩家实测开挂!诸暨翻财神ai开... 玩家实测开挂!诸暨翻财神ai开挂多功能插件,真是有开挂教程经验是一款可以让一直输的玩家,快速成为一个...
记者发布透视!多多休闲ai透视... 您好,记者发布透视!多多休闲ai透视多功能插件,从来是有透视安装要领这款游戏可以开挂的,确实是有挂的...
推荐十款!透视挂!友乐广西麻将... 推荐十款!透视挂!友乐广西麻将ai透视挂多功能插件,都是真的有透视挂平台指引是一款可以让一直输的玩家...
实测揭晓!透视!渝都麻将ai透... 您好:渝都麻将这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别好,...
玩家实测辅助!乐汇娱乐ai辅助... 玩家实测辅助!乐汇娱乐ai辅助多功能插件,原先真的是有辅助方法方针是一款可以让一直输的玩家,快速成为...
科普常识透视!逍遥麻将ai透视... 逍遥麻将AI 游戏攻略黑科技上线本地缓存功能,离线查阅能力开挂。提前下载对应游戏攻略数据包,断网状态...