使用Angular 12 Material Tables显示数据
本教程将教你如何在Angular Material表中显示数据。我们将建立一个完整的项目,用于在Angular Material表中显示数据。
前提条件
要继续学习本教程,你需要具备以下条件。
- 一些关于Angular的背景知识。在本教程中,我们将使用Angular 12。
- 关于使用Angular Material的知识。这将帮助你更快地入门。
- 在你的机器上创建一个Angular项目。
开始使用Angular Material
在本节中,我将向你展示如何设置你的Angular项目以使用Angular Material。
在你的项目根部,打开终端并运行以下命令。
ng add @angular/material
该命令将提示yes/no 问题,如下图所示。
.......
# installation starts
✔ Found compatible package version: @angular/material@12.1.3.
# ..................
Would you like to proceed? (Y/n)
输入y ,继续进行Angular Material的安装。这将安装Material所需的所有软件包。

现在我们已经成功地安装了Material,现在让我们把Material模块导入我们的项目中。
创建一个新文件src/app/app.material-module.ts ,并添加以下代码。
import {NgModule} from '@angular/core';
import {MatTableModule} from '@angular/material/table';
import {MatPaginatorModule} from '@angular/material/paginator';
import {MatInputModule} from '@angular/material/input';
import {MatProgressSpinnerModule} from '@angular/material/progress-spinner';
import {MatSortModule} from '@angular/material/sort';
@NgModule({
// since we're exporting these modules, add them to export
exports: [
MatTableModule,
MatSortModule,
MatProgressSpinnerModule,
MatInputModule,
MatPaginatorModule,
]
})
export class AppMaterialModule {}
在上面的模块中,我们已经从@angular/material/* 中导入了Material模块。然后我们将导出所有这些模块,因为我们将在我们的主模块(app.module.ts )中使用它们。
打开你的app.module.ts 文件,在imports 数组中导入AppMaterialModule 。
// ..........................
import { AppMaterialModule } from "./app.material-module";
@NgModule({
declarations: [
// ....
],
imports: [
// .........
AppMaterialModule,
],
// ...
})
export class AppModule { }
我们已经通过导入AppMaterialModule 模块更新了我们的app.module.ts ,以暴露我们导入的材料模块。
使用材料表来显示数据
在本节中,我将向你展示如何创建材料表来显示一些学生信息。该表将包括基本的学生信息,如names 和registrations 。
让我们从创建细节界面开始。
在你的项目根目录下运行以下命令来创建学生界面。
ng g i student
这将在app/student.ts 文件中创建一个界面。
继续并编辑它,使其看起来如下。
export interface Student {
firstName:string;
lastName:string;
studentEmail:string;
course:string;
yearOfStudy: bigint;
registrationNumber:string;
}
创建一个src/assets/students.json 文件并定义我们将在表中使用的学生详细信息。
[
{
"firstName": "John",
"lastName": "Doe",
"studentEmail": "johndoe@example.com",
"course": "Bsc Software Engineering",
"yearOfStudy": 2
},
{
"firstName": "Test2",
"lastName": "Test2",
"studentEmail": "test@example.com",
"course": "Bsc Computer Science",
"yearOfStudy": 4
}
]
然后在/src/environments/environment.ts 中定义baseURL ,作为一个环境变量。
// ...
export const environment = {
// ...
baseURL:'assets/',
};
// ...
通过运行以下命令创建一个api 服务。
ng g s api
然后按以下方式更新它。
// ...
//import student interface
import {Student} from "../student";
//import this to make http requests
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs";
//we've defined our base url here in the env
import {environment} from "../../environments/environment";
// ....
//class apiService
export class ApiService {
constructor(private httpClient: HttpClient) { }
/**
* This method returns students details
*/
getStudentsInformation(): Observable<Student[]>{
return this.httpClient.get<Student[]>(`${environment.baseURL}student.json`);
}
}
现在,我们已经有了从API获取数据的逻辑,让我们继续,并将其添加到控制器中。
首先,让我们更新我们的app.module.ts 文件如下。
// ...
import { HttpClientModule} from "@angular/common/http";
@NgModule({
declarations: [
// ...
],
imports: [
// ...
HttpClientModule, //endsure your import this module
],
// ...
})
// ...
然后更新app.component.ts 的内容,如下所示。
// ...
import {Component, OnInit} from '@angular/core';
import {MatTableDataSource} from "@angular/material/table";
import {Student} from "./student";
import {ApiService} from "./services/api.service";
@Component({
// ...
})
export class AppComponent implements OnInit{
student: Student[] = [];
// columns we will show on the table
public displayedColumns = ['firstName', 'lastName', 'studentEmail', 'yearOfStudy', 'registrationNumber', 'course' ];
//the source where we will get the data
public dataSource = new MatTableDataSource<Student>();
//dependency injection
constructor(private studentApiService: ApiService) {
}
ngOnInit(){
//call this method on component load
this.getStudentsInformation();
}
/**
* This method returns students details
*/
getStudentsInformation(){
this.studentApiService.getStudentsInformation()
.subscribe((res)=>{
console.log(res);
this.dataSource.data = res;
})
}
}
在这一点上,你现在可以通过使用下面的步骤记录你的API响应可观察输出来测试你的应用程序。
- 通过运行
ng serve --port 3000来服务你的应用程序。 - 转到你的浏览器并打开新标签,然后输入
localhost:3000。 Ctrl + Shift + I以进入日志。
如果你正确地按照上面的步骤操作,你会看到下面的输出。
输出。


现在让我们更新一下我们的app.component.html ,如下图所示,以显示我们的数据。
<table mat-table [dataSource]="dataSource">
<ng-container matColumnDef="firstName">
<th mat-header-cell *matHeaderCellDef> First Name </th>
<td mat-cell *matCellDef="let element"> {{element.firstName}} </td>
</ng-container>
<ng-container matColumnDef="lastName">
<th mat-header-cell *matHeaderCellDef> Last Name </th>
<td mat-cell *matCellDef="let element"> {{element.lastName}} </td>
</ng-container>
<ng-container matColumnDef="studentEmail">
<th mat-header-cell *matHeaderCellDef> Student Email </th>
<td mat-cell *matCellDef="let element"> {{element.studentEmail }} </td>
</ng-container>
<ng-container matColumnDef="registrationNumber">
<th mat-header-cell *matHeaderCellDef> Registration Number </th>
<td mat-cell *matCellDef="let element"> {{element.registrationNumber}} </td>
</ng-container>
<ng-container matColumnDef="course">
<th mat-header-cell *matHeaderCellDef> Course </th>
<td mat-cell *matCellDef="let element"> {{element.course}} </td>
</ng-container>
<ng-container matColumnDef="yearOfStudy">
<th mat-header-cell *matHeaderCellDef> Year Of Study </th>
<td mat-cell *matCellDef="let element"> {{element.yearOfStudy}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
然后打开你的app.component.css 文件,添加以下CSS代码。
table {
width: 100%;
overflow-x: auto;
overflow-y: hidden;
min-width: 500px;
}
th.mat-header-cell {
text-align: left;
max-width: 300px;
}
现在你应该看到下面的表格。

结论
在本教程中,我们已经讨论了Angular材质表。我们看到了如何使用Angular材质表来显示数据。
我希望这篇文章为你使用Angular Material表格打下了坚实的基础。在此基础上,你就可以对你的表格进行分类或添加其他功能。