在 Angular 10 中,可以通过使用 Angular Material 的 mat-table 组件来实现可展开行的表格。下面是一个包含代码示例的解决方法:
首先,确保已经安装了 Angular Material 和 Angular CDK。可以使用以下命令进行安装:
npm install @angular/material @angular/cdk
接下来,在 app.module.ts 文件中导入所需的 Angular Material 模块,并将其添加到 imports 数组中:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatTableModule } from '@angular/material/table';
import { MatExpansionModule } from '@angular/material/expansion';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatTableModule,
MatExpansionModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
然后,在 app.component.ts 文件中创建一个数据源数组和一个方法来切换行的展开状态:
import { Component } from '@angular/core';
interface DataItem {
name: string;
age: number;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
dataSource: DataItem[] = [
{ name: 'John Doe', age: 30 },
{ name: 'Jane Smith', age: 25 },
{ name: 'Bob Johnson', age: 35 }
];
expandedRow: DataItem | null;
toggleRow(row: DataItem) {
if (this.expandedRow === row) {
this.expandedRow = null;
} else {
this.expandedRow = row;
}
}
}
然后,在 app.component.html 文件中使用 mat-table 和 mat-expansion-panel 组件来创建可展开行的表格:
Name
{{row.name}}
Age
{{row.age}}
{{row.name}} ({{row.age}})
Additional content here...
最后,将 app.component.css 文件中的样式添加到表格中,以确保适当的样式和布局:
table {
width: 100%;
}
.mat-row.expanded {
background-color: #f5f5f5;
}
通过以上步骤,你就可以在 Angular 10 中创建一个具有可展开行的 mat-table 了。当点击行时,展开或收缩相应的行内容。