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 |

相关内容

热门资讯

透视辅助!wepoke辅助技巧... 透视辅助!wepoke辅助技巧,wepoke透明挂辅助软件是真的吗,详细透视玩家教你1、wepoke...
微扑克辅助器ios!wpk a... 微扑克辅助器ios!wpk ai辅助有没有用(透视)好像真的有挂(详细辅助AI教程)1、微扑克辅助器...
透视苹果版!wepok软件透明... 透视苹果版!wepok软件透明挂,wepoke的机制,详细透视我来教教你1、wepok软件透明挂透视...
wepoke的确有挂!微扑克辅... 自定义wepoke的确有挂系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅助器,...
wpk外挂!wpk俱乐部24小... wpk外挂!wpk俱乐部24小时(透视)果然真的是有挂(详细辅助扑克教程);wpk外挂!wpk俱乐部...
透视计算!wepoke计算辅助... 透视计算!wepoke计算辅助,wepoke免费软件透明挂,详细透视切实教程wepoke计算辅助辅助...
德州ai人工智能!wepoke... 德州ai人工智能!wepoke是不是有挂(透视)起初有挂(详细辅助大神讲解);无聊就玩这款德州ai人...
透视总结!wepower辅助器... 透视总结!wepower辅助器,wepoke软件下载,详细透视曝光教程;1、让任何用户在无需wepo...
微扑克ai辅助工具!微扑克有机... 微扑克ai辅助工具!微扑克有机器人吗(透视)果然真的有挂(详细辅助教你攻略)是一款可以让一直输的玩家...
透视教学!wepoke真的有挂... 透视教学!wepoke真的有挂,wepower使用说明书,详细透视揭秘攻略1、点击下载安装,wepo...