【问题标题】:How to put distinct buttons in Angular mat-table?如何在 Angular mat-table 中放置不同的按钮?
【发布时间】:2021-07-20 05:51:18
【问题描述】:

我正在使用角度垫表来显示如下所示的数据数组,并进行简单排序。最后一列是一列按钮。我想在每一行中都有不同的按钮来路由到不同的组件。

Array as a table

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

  <!-- SerialNo Column -->
  <ng-container matColumnDef="serialNo">
    <th mat-header-cell *matHeaderCellDef > SerialNo </th>
    <td mat-cell *matCellDef="let device"> {{device.serialNo}} </td>
  </ng-container>

<!-- Button Column -->
  <ng-container matColumnDef="actions">
    <th mat-header-cell  *matHeaderCellDef > Actions </th>
    <td mat-cell *matCellDef="let row" >
      <button mat-button routerLinkActive="list-item-active" routerLink="/device1" >View</button>
    </td>

我的component.ts是这样的。

export interface Devices {
  name: string;
  position: number;
  serialNo: number;
}
//An Array of device1
const DEVICES: Devices[] = [
  {position: 1, name: 'Device 1', serialNo: 135421},
  {position: 2, name: 'Device 2', serialNo: 125240},
  {position: 3, name: 'Device 3', serialNo: 124350},
  {position: 4, name: 'Device 4', serialNo: 124500},
  {position: 5, name: 'Device 5', serialNo: 145620},
];

  displayedColumns: string[] = ['position', 'name', 'serialNo', 'actions'];
  dataSource = new MatTableDataSource(DEVICES);

  @ViewChild(MatSort) sort: MatSort;

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
  }

如何在每一行中添加不同的按钮,使用 routerLink 路由到不同的组件。

【问题讨论】:

    标签: arrays angular button angular-material


    【解决方案1】:

    您要将每个链接重定向到不同的 angular 组件,还是要将每个链接重定向到相同的 angular 组件(例如,device detail 组件),但具有不同的 url 和设备信息(例如重定向到 '/device/1'、'device/2' 等)?

    如果是后者,假设你想将每个设备重定向到一个角度路由'/device-detail/:id',其中id是设备的标识。为简单起见,假设 idserialNo。所以你只需要更改按钮声明。将routerLink="/device1" 替换为[routerLink]="['/device-detail', device.serialNo]"(我也将*matCellDef="let row" 更改为*matCellDef="let device"):

    <td mat-cell *matCellDef="let device" >
       <button mat-button routerLinkActive="list-item-active" [routerLink]="['/device-detail', device.serialNo]" >View</button>
    </td>
    

    【讨论】:

    • 是的,这正是我想要做的。感谢您的帮助!
    猜你喜欢
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    相关资源
    最近更新 更多