我的 Angular 总结:为 AgGridAngular 自定义单元格组件创建基类

136 阅读1分钟

ag-grid-angular 是一个在 Angular 中展示数据表格的强大库。

以下是来自 ag-grid-angular 官网 的一段代码,关于自定义属性(custom props)的使用:

image.png

但我并没有按照这种方式来使用它。接下来我会展示我在创建自定义单元格组件时的做法。


创建一个基类(Base Class)

首先,我会在另一个文件中创建一个抽象类,用于消除三个重复的 onClick 实现。例如:

@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,视需求而定
  }
}

然后,实际的自定义组件代码如下:

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,并可选地声明自定义参数类型即可。

无需再重复定义参数类型、赋值逻辑,也不用重复实现类似的 agInitrefresh 方法。


导出自定义参数类型

顺便提一下,我还会导出自定义参数类型(如上面例子中的 CustomButtonParams),并在列定义一侧使用它:

image.png

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