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 |

相关内容

热门资讯

开挂辅助!雀友会潮汕麻将开挂辅... 开挂辅助!雀友会潮汕麻将开挂辅助,wepoker永久免费脚本(透视)开挂辅助软件(的确有挂);1、很...
辅助开挂!博弈麻友圈辅助,we... 辅助开挂!博弈麻友圈辅助,we poker游戏下(透视)开挂辅助插件(有挂教程);亲,有的,ai轻松...
开挂辅助!九九山城辅助,红龙p... 开挂辅助!九九山城辅助,红龙poker辅助(透视)开挂辅助插件(有挂规律);是一款可以让一直输的玩家...
辅助开挂!拼十app辅助,we... 辅助开挂!拼十app辅助,wepoker透视有吗(透视)开挂辅助工具(有挂分析);拼十app辅助软件...
辅助开挂!hhpoker有没有... 辅助开挂!hhpoker有没有作比,智星德州有脚本吗(透视)开挂辅助插件(有挂教程);1.hhpok...
辅助开挂!丽水都莱大菠萝辅助,... 辅助开挂!丽水都莱大菠萝辅助,wepoker永久免费脚本(透视)开挂辅助插件(有挂透明挂);丽水都莱...
辅助开挂!闽游互动辅助器,we... 辅助开挂!闽游互动辅助器,werplan辅助软件(透视)开挂辅助安装(发现有挂);1、让任何用户在无...
开挂辅助!微信小程序挂机辅助,... 开挂辅助!微信小程序挂机辅助,德普之星辅助工具如何设置(透视)开挂辅助插件(有挂攻略);超受欢迎的微...
辅助开挂!广西老友麻将有挂吗,... 辅助开挂!广西老友麻将有挂吗,wepoker俱乐部辅助器(透视)开挂辅助插件(有挂分析);小薇(透视...
辅助开挂!微信小程序挂后台,h... 辅助开挂!微信小程序挂后台,hhpoker脚本下载(透视)开挂辅助脚本(真的有挂);微信小程序挂后台...