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有人玩吗,法门教程(竟然真的是有挂)-哔哩哔...
透视安卓版本!cloudpok... 透视安卓版本!cloudpoker怎么开挂(透视)开挂辅助插件(确实是真的挂)-哔哩哔哩1、clou...
透视攻略!德扑圈透视,wepo... 透视攻略!德扑圈透视,wepoker插件下载,手段教程(其实真的有挂)-哔哩哔哩1、很好的工具软件,...
透视测试!we-poker正规... 透视测试!we-poker正规吗(透视)开挂辅助工具(真是存在有挂)-哔哩哔哩1、每一步都需要思考,...
透视数据!德州局透视脚本下载安... 透视数据!德州局透视脚本下载安装最新版本,wpk辅助插件,秘籍教程(原来是真的挂)-哔哩哔哩1、这是...
透视系统!wepoker怎么获... 透视系统!wepoker怎么获得好牌(透视)开挂辅助神器(本来是真的挂)-哔哩哔哩1、下载好wepo...
透视游戏!sohoo竞技联盟辅... 透视游戏!sohoo竞技联盟辅助器,wepoker透视脚本免费使用视频,妙招教程(确实是有挂)-哔哩...
透视透视!hh poker辅助... 透视透视!hh poker辅助器先试用(透视)开挂辅助攻略(都是存在有挂)-哔哩哔哩1、任何hh p...
透视教学!约局吧德州真的有透视... 透视教学!约局吧德州真的有透视挂吗,sohoo竞技联盟辅助器,手段教程(竟然存在有挂)-哔哩哔哩约局...
透视神器!aapoker透视插... 透视神器!aapoker透视插件(透视)开挂辅助挂(真是真的有挂)-哔哩哔哩1、操作简单,无需注册,...