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 |

相关内容

热门资讯

科技介绍!腾微填大坑辅助,so... 科技介绍!腾微填大坑辅助,sohoo poker辅助,总结教程(有挂透明挂);科技介绍!腾微填大坑辅...
一分钟了解!微友辅助神器下载,... 您好:微友辅助神器下载这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌...
终于懂了!天天贵阳游戏辅助,h... 终于懂了!天天贵阳游戏辅助,hhpoker是正品吗,靠谱教程(有挂技巧);天天贵阳游戏辅助最新版本免...
每日必看!雀友会钻石辅助器潮汕... 每日必看!雀友会钻石辅助器潮汕麻将,wepoker怎么增加运气,专业教程(有挂头条);详细雀友会钻石...
查到实测!皇豪互众智能辅助器,... 查到实测!皇豪互众智能辅助器,pokemmo手机脚本辅助器,扑克教程(有挂规律)相信很多朋友都在电脑...
玩家必看科普!雀神广东麻雀智能... 玩家必看科普!雀神广东麻雀智能科技贴吧,wepoker透视脚本是什么,新2025版(有挂方针);人气...
盘点十款!超级三加一辅助工具安... 盘点十款!超级三加一辅助工具安装,德普之星透视免费,详细教程(确实有挂);1、让任何用户在无需AI插...
一分钟快速了解!同乡游有辅助软... 一分钟快速了解!同乡游有辅助软件码,newpoker脚本,揭秘教程(有挂工具);同乡游有辅助软件码是...
记者发布!四川途游防作弊,hh... 记者发布!四川途游防作弊,hhpoker怎么防作弊,切实教程(有挂解密);四川途游防作弊软件透明挂作...
今日重大通报!佛手大菠萝破解版... 今日重大通报!佛手大菠萝破解版ios,wepoker辅助软件价格,攻略教程(有挂细节);1、不需要A...