Angular12 如何在employee-edit跳转后触发employee-detail的指定显示方法
Angular12 跨组件跳转后自动激活对应模块实现方案
步骤1:修改编辑页跳转逻辑,传递标识参数
在employee-edit.component.ts的两个提交方法中,跳转时新增参数标记当前提交的模块类型:
onSubmitProfile() { // 跳转时携带查询参数,标记要激活profile模块 this.router.navigate(['/employees-detail', this._id], { queryParams: { activeTab: 'profile' } }); } onSubmitContact() { // 跳转时携带查询参数,标记要激活contact模块 this.router.navigate(['/employees-detail', this._id], { queryParams: { activeTab: 'contact' } }); }
步骤2:修改详情页,接收参数自动触发对应方法
首先在employee-detail.component.ts中导入OnInit和ActivatedRoute,注入路由服务后在初始化钩子中读取参数触发对应逻辑:
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ // 你的组件原有配置 }) export class EmployeeDetailComponent implements OnInit { profileTemplate: boolean = false; contactTemplate: boolean = false; // 注入ActivatedRoute用于读取路由参数 constructor(private route: ActivatedRoute) {} ngOnInit(): void { // 监听查询参数变化 this.route.queryParams.subscribe(params => { const activeTab = params['activeTab']; if (activeTab === 'profile') { this.profileFunction(); } else if (activeTab === 'contact') { this.contactFunction(); } }); } profileFunction() { this.profileTemplate = true; this.contactTemplate = false; } contactFunction() { this.profileTemplate = false; this.contactTemplate = true; } }
可选优化:隐藏地址栏参数
如果不想让activeTab参数显示在浏览器地址栏,可以改用Angular路由的state属性传递参数:
- 编辑页跳转逻辑修改为:
onSubmitProfile() { this.router.navigate(['/employees-detail', this._id], { state: { activeTab: 'profile' } }); } onSubmitContact() { this.router.navigate(['/employees-detail', this._id], { state: { activeTab: 'contact' } }); }
- 详情页读取参数逻辑修改为:
ngOnInit(): void { const activeTab = history.state?.activeTab; if (activeTab === 'profile') { this.profileFunction(); } else if (activeTab === 'contact') { this.contactFunction(); } }
内容的提问来源于stack exchange,提问作者user11352561
相关产品推荐
相关产品推荐

