Angular Material 7 – 表格

Angular Material 7 – 表格

Angular Material是一个使用Angular框架来设计和开发精美的Web应用程序的开发工具包。其中,表格是Angular Material中一个非常常用的组件,本文将探讨如何使用Angular Material 7创建和使用表格。

创建Angular Material表格

首先,需要安装Angular Material和Angular CDK。打开终端并输入以下命令:

npm install --save @angular/material @angular/cdk

接下来,需要在Angular模块中导入MatTableModule模块。打开模块文件(通常是 app.module.ts)并添加以下代码:

import { MatTableModule } from '@angular/material/table';

@NgModule({
  imports: [
    MatTableModule,
    ...
  ],
  ...
})
export class AppModule { }

在组件代码中,需要定义数据对象并调用MatTableDataSource类。以下是一个简单的示例:

import { Component } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';

export interface UserData {
  id: string;
  name: string;
  progress: string;
}

const ELEMENT_DATA: UserData[] = [
  {id: '1', name: 'Yip', progress: '30'},
  {id: '2', name: 'Gloria', progress: '50'},
  {id: '3', name: 'Sam', progress: '70'},
];

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  displayedColumns: string[] = ['id', 'name', 'progress'];
  dataSource = new MatTableDataSource(ELEMENT_DATA);
}

接下来,在组件的HTML文件中添加以下代码,以显示表格:

<table mat-table [dataSource]="dataSource">

  <!-- Position Column -->
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef> ID </th>
    <td mat-cell *matCellDef="let element"> {{element.id}} </td>
  </ng-container>

  <!-- Name Column -->
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>

  <!-- Progress Column -->
  <ng-container matColumnDef="progress">
    <th mat-header-cell *matHeaderCellDef> Progress </th>
    <td mat-cell *matCellDef="let element"> {{element.progress}}% </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

这将显示以下表格:

ID Name Progress
1 Yip 30%
2 Gloria 50%
3 Sam 70%

常用表格操作

懒加载数据

在应用程序中,要显示大量数据的表格时,最好使用懒加载模式。这样,只有在用户滚动到页面的底部时才会获取新的数据。以下是如何实现懒加载数据的示例代码:

export class AppComponent {
  displayedColumns: string[] = ['id', 'name', 'progress'];
  dataSource = new MatTableDataSource();

  @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
  @ViewChild(MatSort, {static: true}) sort: MatSort;

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;

    this.dataService.getUserData()
      .subscribe(data => {
        this.dataSource.data = data;
      });
  }
}

在这个示例中,使用MatPaginatorMatSort分别分页和排序。使用ViewChild注解引用了这两个组件。使用OnInit生命周期钩子,导入数据并将其分配给适当的表格数据源。

过滤

使用MatTableDataSource类,可以实现内置的过滤功能。只需设置filterPredicate属性以指定如何对数据进行过滤。以下是一个示例:

export class AppComponent {
  displayedColumns: string[] = ['id', 'name', 'progress'];
  dataSource = new MatTableDataSource();

  ...

  ngOnInit() {
    this.dataSource.filterPredicate = (data: UserData, filter: string) => {
      return data.name.toLowerCase().includes(filter) || data.id.toString() === filter;
    };
  }

  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }
}

在这个示例中,使用filterPredicate将输入的文本分配到数据源的filter属性中。

手动排序

在某些情况下,可能需要在不使用MatSort的情况下手动排序表格。以下是一个示例:

export class AppComponent {
  displayedColumns: string[] = ['id', 'name', 'progress'];
  dataSource = new MatTableDataSource();

  ...

  sortBy(col: string) {
    const sortState: Sort = {active: col, direction: 'asc'};
    this.dataSource.sort = {
      ...this.dataSource.sort,
      ...sortState
    };
    this.dataSource.data = this.dataSource.sortData(this.dataSource.data, this.dataSource.sort);
  }
}

在这个示例中,使用Sort接口定义了表格的当前排序状态。然后,使用sortBy方法指定需要排序的列,并手动对数据进行排序。

定制表格

使用Angular Material表格时,允许对表格的外观进行许多修改和自定义。以下是一些常见的定制方法:

更改颜色

要更改表格头部的颜色,需要应用新的样式。以下是一个示例:

.mat-header-cell {
  background-color: #3f51b5;
  color: white;
}

这将更改表格头的背景色和字体颜色。

更改边框

同样可以使用CSS来更改表格的边框。以下是一个示例:

table {
  border-collapse: separate;
  border-spacing: 0 10px;
  border: 1px solid black;
}

这将在表格单元格之间添加空白,以及添加黑色的实线边框。

添加复选框

在表格中添加复选框,需要使用MatCheckboxModule模块来创建相应的复选框元素。以下是一个示例:

<table mat-table [dataSource]="dataSource">

  <ng-container matColumnDef="select">
    <th mat-header-cell *matHeaderCellDef>
      <mat-checkbox (change)="event ? masterToggle() : null"
                    [checked]="selection.hasValue() && isAllSelected()"
                    [indeterminate]="selection.hasValue() && !isAllSelected()">
      </mat-checkbox>
    </th>
    <td mat-cell *matCellDef="let element">
      <mat-checkbox (click)="event.stopPropagation()"
                    (change)="$event ? selection.toggle(element) : null"
                    [checked]="selection.isSelected(element)">
      </mat-checkbox>
    </td>
  </ng-container>

  <!-- rest of the columns -->

</table>

在这个示例中,使用selection变量来跟踪选定的行,并使用mat-checkbox元素添加复选框。

添加操作按钮

为表格添加操作按钮,需要使用MatIconModule模块以及mat-icon元素插入所需的图标。以下是一个示例:

<table mat-table [dataSource]="dataSource">

  <!-- columns -->

  <ng-container matColumnDef="actions">
    <th mat-header-cell *matHeaderCellDef></th>
    <td mat-cell *matCellDef="let element">
      <button mat-icon-button color="primary" (click)="editElement(element)">
        <mat-icon>edit</mat-icon>
      </button>
      <button mat-icon-button color="accent" (click)="deleteElement(element)">
        <mat-icon>delete</mat-icon>
      </button>
    </td>
  </ng-container>

</table>

在这个示例中,使用mat-icon-button元素添加操作按钮,并使用mat-icon元素插入图标。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程