ag-grid-angular
是一个在 Angular 中展示数据表格的强大库。
以下是来自 ag-grid-angular
官网 的一段代码,关于自定义属性(custom props)的使用:

但我并没有按照这种方式来使用它。接下来我会展示我在创建自定义单元格组件时的做法。
创建一个基类(Base Class)
首先,我会在另一个文件中创建一个抽象类,用于消除三个重复的 onClick
实现。例如:
ts
@Component({
template: ``,
})
export abstract class CellRendererBaseComponent<
TParams extends ICellRendererParams = ICellRendererParams
> implements ICellRendererAngularComp
{
protected params!: TParams;
agInit(params: TParams): void {
this.params = params;
}
refresh(params: TParams) {
return false; // 默认可设为 true,视需求而定
}
}
然后,实际的自定义组件代码如下:
ts
import { ChangeDetectionStrategy, Component } from "@angular/core";
import type { ICellRendererAngularComp } from "ag-grid-angular";
import type { ICellRendererParams } from "ag-grid-community";
interface CustomButtonParams extends ICellRendererParams {
onClick: () => void;
}
@Component({
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<button (click)="params.onClick()">Launch!</button>`,
})
export class CustomButtonComponent extends CellRendererBaseComponent<CustomButtonParams> {}
如果还有另一个自定义组件,比如 CustomButton2Component
,你只需要继承 CellRendererBaseComponent
,并可选地声明自定义参数类型即可。
无需再重复定义参数类型、赋值逻辑,也不用重复实现类似的 agInit
和 refresh
方法。
导出自定义参数类型
顺便提一下,我还会导出自定义参数类型(如上面例子中的 CustomButtonParams
),并在列定义一侧使用它:

这样,当类型不匹配时,你会立刻看到类型错误提示,提升类型安全性与开发体验。