Angular路由会保持先前的组件显示,并且不完全加载下一个组件。
创始人
2024-10-28 02:00:24
0

在Angular中,路由默认是在加载新组件时销毁先前的组件。如果你想保持先前的组件显示,并且不完全加载下一个组件,你可以使用标签来实现。

首先,在你的父组件的模板中添加一个标签,用于显示路由组件。例如:


然后,在你的路由配置中,将component属性替换为loadChildren属性,并将组件加载到ComponentFactoryResolver中。例如:

import { ComponentFactoryResolver } from '@angular/core';

const routes: Routes = [
  {
    path: 'your-path',
    loadChildren: () => import('./your-component/your-component.module').then(m => m.YourComponentModule)
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

在你的YourComponentModule中,使用ComponentFactoryResolver来加载组件并将其添加到DOM中。例如:

import { ComponentFactoryResolver, ComponentRef, ViewContainerRef, OnInit } from '@angular/core';
import { YourComponent } from './your-component.component';

@Component({
  selector: 'app-your-component',
  template: ''
})
export class YourComponentModule implements OnInit {
  @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
  componentRef: ComponentRef;

  constructor(private componentFactoryResolver: ComponentFactoryResolver) { }

  ngOnInit() {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(YourComponent);
    this.componentRef = this.container.createComponent(componentFactory);
  }
}

这样,当你导航到your-path时,先前的组件将保持显示,并且新组件将被加载到DOM中。

请注意,这种方法可能会导致性能问题,因为每次导航时都会加载新组件。因此,你应该慎重使用这种方法,并确保你的应用程序可以处理大量组件的加载和销毁。

相关内容

热门资讯

透视教学“pokeplus脚本... 透视教学“pokeplus脚本”透视辅助工具(切实真的是有挂)1、pokeplus脚本系统规律教程、...
透视黑科技!德普之星私人局辅助... 透视黑科技!德普之星私人局辅助免费,(德普之星)总是是有挂,靠谱教程(有挂揭秘)所有人都在同一条线上...
透视免费!pokerworld... 透视免费!pokerworld修改器,pokermaster脚本,大神讲解(有挂脚本);该软件可以轻...
透视玄学!德扑圈透视,(德扑之... 透视玄学!德扑圈透视,(德扑之心)原来真的有挂,必备教程(有挂介绍)1、构建自己的德扑圈透视辅助插件...
透视软件!大菠萝789辅助器下... 透视软件!大菠萝789辅助器下载,德州来玩辅助器,揭秘攻略(有挂技巧)1、玩家可以在大菠萝789辅助...
透视讲解!德普软件,德普之星辅... 透视讲解!德普软件,德普之星辅助器怎么用,安装教程(有挂介绍)1、让任何用户在无需德普之星辅助器怎么...
透视新版“werplan辅助软... 透视新版“werplan辅助软件”透视辅助助手(总是有挂)1、不需要AI权限,帮助你快速的进行wer...
透视挂!德普之星辅助软件,(德... 透视挂!德普之星辅助软件,(德普之星)好像是有挂,新2025版(有挂教程);1、点击下载安装,德普之...
透视最新“智星菠萝辅助”透视辅... 透视最新“智星菠萝辅助”透视辅助脚本(一贯真的有挂)1、玩家可以在智星菠萝辅助软件透明挂俱乐部对游戏...
透视最新!德普之星透视,德普之... 透视最新!德普之星透视,德普之星辅助器app,黑科技教程(有挂详情)1)德普之星辅助器app辅助挂:...