我们在用 AngularJS 开发前端时,难免会用到表格,我们首先会想到使用 ag-grid,因其号称是世界上最好的 JavaScript 数据表格。本文记录如何增加 操作栏 列,具体如下:

增加一个 CellRendererFramework Component

import { Component } from "@angular/core";
import { ICellRendererAngularComp } from 'ag-grid-angular';
import { ICellRendererParams } from "ag-grid-community";

@Component({
    selector: 'action-renderer-component',
    template: `
        <button class="far fa-trash-alt" (click)="handleDelete()"></button>
    `
})
export class ActionRendererComponent implements ICellRendererAngularComp {
    public cellValue: string;
    public params: ICellRendererParams;

    agInit(params: ICellRendererParams): void {
        this.params = params
        this.cellValue = this.getValueToDisplay(params);
    }

    refresh(params: ICellRendererParams): boolean {
        this.cellValue = this.getValueToDisplay(params);
        return true;
    }

    handleDelete() { // this.params.context.componentParent 为 gridOptions 中定义的内容
        this.params.context.componentParent.onRowDelete(this.cellValue, this.params.rowIndex)
    }

    getValueToDisplay(params: ICellRendererParams) {
        return params.valueFormatted ? params.valueFormatted : params.value;
    }
}

gridOptions 中增加一个上下文,并使用上面自定义 CellRendererFramework Component

this.gridOptions = <GridOptions>{
    context: {
        componentParent: this // 将表格组件的上下文放在这里面
    },
    columnDefs : this.makeColumnDefs()
}

private makeColumnDefs(): any {
    return [
        {
            headerName: `Action`,
            field: 'id',
            width: 100,
            filter: false,
            editable: false,
            cellRendererFramework: ActionRendererComponent
        }
    ]
}
如果觉得我的文章对你有用,请点个赞