实现思路
- 配置多层嵌套路由:在Angular的路由模块中,使用
children
属性来定义嵌套路由结构。例如:
const routes: Routes = [
{
path: 'parent',
component: ParentComponent,
children: [
{
path: 'child1',
component: Child1Component
},
{
path: 'child2',
component: Child2Component
}
]
}
];
- 动态加载组件:使用
RouterOutlet
和ActivatedRoute
。在需要动态加载组件的父组件模板中,使用RouterOutlet
来渲染子路由组件。同时,利用ActivatedRoute
获取路由参数或通过router.events
监听路由变化来决定加载哪个动态组件。
- 状态管理:
- 初始化:在组件的
ngOnInit
生命周期钩子函数中进行初始化操作,如获取数据、绑定事件等。
- 销毁:在组件的
ngOnDestroy
生命周期钩子函数中进行清理操作,如取消订阅Observable、解绑事件等。
关键代码要点
- 动态加载组件的父组件模板:
<router-outlet></router-outlet>
- 动态加载组件的父组件TS代码:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.params.subscribe(params => {
// 根据参数决定加载哪个动态组件,例如:
if (params['dynamicComponent'] === 'component1') {
// 逻辑处理
}
});
}
}
- 动态加载组件的TS代码(以Child1Component为例):
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-child1',
templateUrl: './child1.component.html',
styleUrls: ['./child1.component.css']
})
export class Child1Component implements OnInit, OnDestroy {
private subscription: Subscription;
ngOnInit() {
this.subscription = this.someObservable.subscribe(data => {
// 处理数据
});
}
ngOnDestroy() {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
}