angular 2 ag-grid 无法读取 getSelectedRow() 未定义的 属性 'api'

angular 2 ag-grid Cannot read property 'api' of undefined by getSelectedRow()

我在一个项目中工作,需要构建一些 table 模板来显示员工信息,协调员选择了一名员工来做某事我遇到了一些来自 API 的问题AgGridModule 但是当我尝试 select 该行以便它可以在控制台日志中显示它时。 但我遇到了一个问题:

StoreComponent.html:2 ERROR TypeError: Cannot read property 'api' of undefined at StoreComponent.push../src/app/Component/store/store.component.ts.StoreComponent.getSelectedRows

谁能帮我解决一下

这是我的代码:- https://stackblitz.com/edit/angular-yfdcbn?file=src%2Fstyles.css

您需要将 #agGrid 添加到您的 HTML 模板,使其看起来像:

<ag-grid-angular  #agGrid
                  style="width: 500px; height: 500px;" 
                  class="ag-theme-balham"
                  [rowData]="rowData "
                  [columnDefs]="columnDefs"
                  rowSelection="multiple"
                  >

这背后的原因是您组件中的变量 agGrid 定义为:@ViewChild('agGrid') agGrid: AgGridNg2;.

因此您需要在 HTML 中定义一个 #agGrid HTML 模板引用变量。您可以找到有关 in the Angular doc.

的更多信息

这个问题是因为你没有定义gridApi;您必须在网格 HTML 的 (gridReady)="onGridReady($event)" 事件中定义 griApi ;你可以像这样在 ts 中使用 onGridReady :

onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;
}

然后您可以获得所选的行:

  getSelectedRows() {
    const selectedRow = this.gridApi.getSelectedRows();
    console.log(selectedRow);
  }

如果卡住了,可以查看示例EXAMPLE

在 angular 6 和 ag-grid 20 中,当您将 Gridoptions 与 rowData & 一起使用并且您正在使用 setRowData() 设置 rowData 时,您可能会看到此问题。一种解决方案是不要配置它并在收到来自 API

的数据后设置 Rowdata