【问题标题】:Implementing a button in ag-grid在 ag-grid 中实现一个按钮
【发布时间】:2021-05-03 19:47:08
【问题描述】:

我正在尝试向 ag-grid 的 this example 学习,以便在网格的每一行中创建一个删除按钮。上述示例有效,但我的代码无效,我不知道为什么。

我正在附上我的代码,希望有人可以帮助我。

home.component.ts:

@Component({
  selector: 'home',
  providers: [
    Title
  ],
  styleUrls: [ './home.component.css' ],
  templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
  private items: Item[] = [];
  private gridOptions:GridOptions;
  private columnDefs = [];

  constructor(
    private itemsService: ItemsService
  ) {
    this.gridOptions = {};
    this.columnDefs = this.createColumnDefs();
  }

  remove() {
    alert("yey!")
  }

  ngOnInit(){
    this.itemsService
      .getAll()
      .subscribe(result => {
        this.items = result;
      });
  }

  private createColumnDefs() {
    return [
      {
        headerName: "Foo",
        field: "foo",
        width: 100,
      },
      {
        headerName: "Bar",
        field: "bar",
        width: 100,
      },
      {
        headerName: "",
        field: "_id",
        cellRendererFramework: RemoveButton,
        colId: "params",
        width: 100
      },
    ];
  }
}

home.component.html:

<div>
      <ag-grid-angular #agGrid style="width: 602px; height: 350px;" class="ag-fresh"
                       [gridOptions]="gridOptions"
                       [columnDefs]="columnDefs"
                       [rowData]="items">
      </ag-grid-angular>
  </div>

RemoveButton.ts:

@Component({
  selector: 'remove-button',
  template: `<span><button style="height: 20px" (click)="remove()">X</button></span>`
})
export class RemoveButton implements ICellRendererAngularComp {
  public params: any;

  agInit(params: any): void {
    this.params = params;
  }

  public remove() {
    this.params.context.componentParent.remove();
  }
}

网格显示所有数据,但单击按钮会产生此错误:

ERROR TypeError: Cannot read property 'componentParent' of undefined
    at RemoveButton.webpackJsonpac__name_.453.RemoveButton.remove

意思是contextparams 是未定义的。

如果需要任何进一步的代码或信息,请告诉我。

【问题讨论】:

    标签: angular ag-grid


    【解决方案1】:

    我已经解决了我的问题。显然context 是未定义的,因为我没有定义它。在gridOptions 中定义上下文解决了这个问题:

    this.gridOptions ={
          context: {
            componentParent: this
          }
        };
    

    【讨论】:

    • 文档没有提到这一点,就像其他文档一样,总是缺少关键方面。我也有同样的问题,不明白为什么。
    • 仅供参考 - 当我在 ag-grid 中实现一个调用父页面上的函数的按钮时,这部分文档 (ag-grid.com/javascript-grid-cell-rendering-components/…) 确实帮助了我。
    • @Maverik 谢天谢地,我不是唯一注意到这一点的人。让我发疯。
    猜你喜欢
    • 2023-03-03
    • 2020-10-18
    • 2018-10-10
    • 2019-11-10
    • 2018-08-30
    • 1970-01-01
    • 2019-08-06
    • 2019-05-23
    • 2021-10-28
    相关资源
    最近更新 更多