import { Component, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, OnDestroy, AfterViewInit } from '@angular/core'; import { RouterOutlet, Router } from '@angular/router';
@Component({
selector: 'app-my-component',
template: '
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(); } } }
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 |