如何在Angular Material DataTables中实现带图标操作按钮的列?
实现Angular Material Table的操作列(带图标按钮链接)
很简单,咱们一步步来,把你原来JS DataTables里的操作列功能迁移到Angular Material Table中,完全匹配你之前的需求:
1. 在模板中添加操作列定义
首先,在你的component.html里,现有列的ng-container之后,新增操作列的定义。这里沿用你原来的CSS类和图标,同时推荐用Angular的routerLink代替原生href(更符合Angular路由的最佳实践),如果要保留原生href直接替换回去即可:
<!-- 新增操作列的定义 --> <ng-container matColumnDef="acciones"> <mat-header-cell *matHeaderCellDef> Acciones </mat-header-cell> <mat-cell *matCellDef="let user"> <!-- 编辑按钮 --> <a [routerLink]="['/categorias/usuarios/detalle', user.id]" class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill" > <i class="fa fa-edit"></i> </a> <!-- 删除按钮 --> <a [routerLink]="['/categorias/usuarios/eliminar', user.id]" class="m-portlet__nav-link btn m-btn m-btn--hover-danger m-btn--icon m-btn--icon-only m-btn--pill" title="Eliminar usuario" > <i class="fa fa-trash"></i> </a> </mat-cell> </ng-container>
2. 更新显示列数组
接下来,在UsuariosComponent的displayedColumns数组里加入新增的acciones列,确保它能被渲染到表格中:
export class UsuariosComponent { dataSource = new UserDataSource(this.UsuariosService); // 添加"acciones"到显示列列表 displayedColumns = [ "id", "nombre", "apellido", "email", "perfil", "ultimoLogin", "activo", "acciones" // 新增这一项 ]; // ... 其他代码保持不变 }
3. 确保Font Awesome图标可用
因为你用到了fa fa-edit和fa fa-trash图标,需要确认项目已引入Font Awesome:
- 可以通过npm安装:
npm install @fortawesome/fontawesome-free,然后在angular.json的styles数组中添加node_modules/@fortawesome/fontawesome-free/css/all.css - 或者直接在
index.html里引入Font Awesome的CDN链接
4. 验证路由配置(可选)
如果使用了routerLink,要确保路由模块中已配置对应规则,比如:
const routes: Routes = [ // ... 其他路由 { path: 'categorias/usuarios/detalle/:id', component: UserDetalleComponent }, { path: 'categorias/usuarios/eliminar/:id', component: UserEliminarComponent }, ];
这样配置完成后,你的Material Table就会和之前JS版本的DataTables效果完全一致:每行末尾显示编辑和删除图标按钮,点击后跳转至对应页面,样式也和原版本保持统一。
内容的提问来源于stack exchange,提问作者Pedro
相关产品推荐
相关产品推荐

