如何在Angular Material Tab间切换并传递CustomerDTO类型数据
Angular Material Tab 切换+客户数据传递实现方案
实现思路
以承载tab的父组件为中间调度层,管理tab的激活索引状态,同时接收表格子组件的编辑事件、将选中的客户数据下发到编辑子组件。
具体实现
1. 父组件新增状态变量
父组件ts文件中添加两个变量,分别控制tab激活状态和存储待编辑的客户数据:
import { Component } from '@angular/core'; import { CustomerDTO } from './customer.dto'; @Component({ selector: 'app-customer', templateUrl: './customer.component.html' }) export class CustomerComponent { // tab激活索引:0对应View tab,1对应Edit tab selectedTabIndex = 0; // 存储待编辑的客户数据 selectedCustomer: CustomerDTO | null = null; // 接收表格组件传递的编辑事件 handleEdit(customer: CustomerDTO): void { this.selectedCustomer = customer; this.selectedTabIndex = 1; } }
2. 修改父组件模板
给mat-tab-group绑定激活索引,给表格组件绑定编辑事件监听,给编辑组件绑定输入参数:
<mat-tab-group [(selectedIndex)]="selectedTabIndex"> <mat-tab label="View"> <div> <app-customer-table (editCustomer)="handleEdit($event)"></app-customer-table> </div> </mat-tab> <mat-tab label="Edit"> <div> <app-customer-create [customer]="selectedCustomer"></app-customer-create> </div> </mat-tab> </mat-tab-group>
3. 表格组件新增编辑事件输出
在app-customer-table组件ts中添加Output事件,点击编辑按钮时触发事件传递当前行客户数据:
import { Component, Output, EventEmitter } from '@angular/core'; import { CustomerDTO } from '../customer.dto'; @Component({ selector: 'app-customer-table', templateUrl: './customer-table.component.html' }) export class CustomerTableComponent { @Output() editCustomer = new EventEmitter<CustomerDTO>(); // 编辑按钮点击触发方法 onEditClick(customer: CustomerDTO): void { this.editCustomer.emit(customer); } }
4. 编辑组件接收客户数据
在app-customer-create组件ts中添加Input属性,接收传递的客户数据后可直接初始化表单:
import { Component, Input, OnInit } from '@angular/core'; import { CustomerDTO } from '../customer.dto'; @Component({ selector: 'app-customer-create', templateUrl: './customer-create.component.html' }) export class CustomerCreateComponent implements OnInit { @Input() customer: CustomerDTO | null = null; ngOnInit(): void { // 存在客户数据时说明是编辑状态,初始化表单 if (this.customer) { this.customerForm.patchValue(this.customer); } } }
可选优化
切换回View tab时清空历史编辑数据,避免下次进入编辑页残留旧数据:
在父组件添加tab切换监听方法:
onTabChange(index: number): void { if (index === 0) { this.selectedCustomer = null; } }
修改模板的mat-tab-group绑定切换事件:
<mat-tab-group [(selectedIndex)]="selectedTabIndex" (selectedIndexChange)="onTabChange($event)">
内容的提问来源于stack exchange,提问作者Tristate
相关产品推荐
相关产品推荐

