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代打辅... 透视攻略!wepoker代打辅助机器人,we poker游戏下(透视)力荐教程(有挂详情)1、每一步...
透视黑科技!wepoker软件... 透视黑科技!wepoker软件辅助程序,wepoker作弊辅助(透视)攻略方法(有挂脚本)1、不需要...
透视中牌率!黑侠破解wepok... 透视中牌率!黑侠破解wepoker,wepoker软件辅助程序(透视)必赢方法(有挂脚本);1、进入...
透视玄学!wepoker有脚本... 透视玄学!wepoker有脚本吗,wepoker有透视功能吗(透视)详细教程(有挂技巧)1、超多福利...
透视私人局!wepoker模拟... 透视私人局!wepoker模拟器哪个,wepoker作弊视频(透视)曝光教程(有挂工具)在进入wep...
透视能赢!wepoker透视脚... 透视能赢!wepoker透视脚本下载,wepoker轻量版书签(透视)靠谱教程(有挂辅助);1)we...
透视ai代打!wepoker挂... 透视ai代打!wepoker挂,wepoker轻量版有透视吗(透视)科技教程(有挂教程);wepok...
透视免费!wepoker私人定... 透视免费!wepoker私人定制透视,wepoker私人局可以透视(透视)高科技教程(有挂解说)该软...
透视ai代打!wepoker脚... 透视ai代打!wepoker脚本,wepokerplus万能挂(透视)教你攻略(有挂插件)1、wep...
透视攻略!wepoker私人局... 透视攻略!wepoker私人局辅助,wepoker亲友圈有用吗(透视)玩家教你(有挂攻略)1、金币登...