繁体   English   中英

以编程方式选择一行 ag-grid + angular 2

[英]Programmatically select a row ag-grid + angular 2

尝试在 ag-grid 中默认选择第一行。 根据 ag-grid 文档,我应该能够使用 NodeSelection Api( https://www.ag-grid.com/javascript-grid-selection/?framework=all#gsc.tab=0 )来做到这一点。 但是我根本无法访问节点对象。 HTML文件

<div class="pulldown panel panel-default">
          <div class="panel-heading">{{rulesSummaryTitle}}</div>
          <ag-grid-angular #agGrid   class="ag-fresh ag-bootstrap"
                           [gridOptions]="gridOptions"
                           [rowData]="rowData"
                           [columnDefs]="columnDefs"
                           [enableSorting]="true"
                           rowSelection="single"
                           [pagination]="true"
                           [suppressCellSelection]="true"
                           (gridReady)="onGridReady($event)"
                           (rowSelected)="onRowSelect($event)">
          </ag-grid-angular>
      </div>

我在“onGridReady”方法中调用节点选择api,但错误消息“cant call setSelected on undefined”。

public onGridReady(event: any): void {
    event.api.sizeColumnsToFit();
    this.gridOptions.api.node.setSelected(true);
  }

gridOptions.api对象上没有node属性。 你会想要做更多这样的事情:

public onGridReady(event: any): void {
    event.api.sizeColumnsToFit();
    gridOptions.api.forEachNode(node=> node.rowIndex ? 0 : node.setSelected(true))
  }

这将检查数据中的每个节点并查看 rowIndex 是否为 0,如果是,则使用节点对象设置 selected 属性

找到解决方案,问题是在从 Observables 填充行数据之前调用了“onGridReady”函数。 所以实际上没有 select 语句可以选择的行。

import { Component } from '@angular/core';
import {Observable} from "rxjs/Observable";
export class Hero {
  id: number;
  name: string;
}

@Component({
  selector: 'my-app',
  template: `
    <ag-grid-angular style="width: 500px; height: 115px;" class="ag-fresh"
                 [rowData]="rowData"
                 (gridReady)="onReady($event)"
                 [columnDefs]="columnDefs">
</ag-grid-angular>
<ag-grid-angular style="width: 500px; height: 115px;" class="ag-fresh"
                 [rowData]="rowData2"
                 (gridReady)="onReady($event)"
                 [columnDefs]="columnDefs">
</ag-grid-angular>
<ag-grid-angular style="width: 500px; height: 115px;" class="ag-fresh"
                 [gridOptions]="gridOptions"
                 [rowData]="rowData3"
                 (gridReady)="onReady($event)"
                 (rowDataChanged)="onRowDataChanged()"
                 [columnDefs]="columnDefs">
</ag-grid-angular>
    `
})
export class AppComponent {
    columnDefs;
    rowData;
    rowData2;
    rowData3;

    constructor() {
      this.gridOptions = {
      rowData: this.rowData3
    };
      console.log("in here");
      console.log("in here");
      console.log("in here");
        this.columnDefs = [
            {headerName: "Make", field: "make"},
            {headerName: "Model", field: "model"},
            {headerName: "Price", field: "price"}
        ];

        this.rowData = [
            {make: "Toyota", model: "Celica", price: 35000},
            {make: "Ford", model: "Mondeo", price: 32000},
            {make: "Porsche", model: "Boxter", price: 72000}
        ]

        let val = [
      {make: "Toyota", model: "Celica", price: 35000},
      {make: "Ford", model: "Mondeo", price: 32000},
      {make: "Porsche", model: "Boxter", price: 72000}
    ];


    let res : Observable<any> = Observable.create(observer => {
      setTimeout(()=>{
        observer.next(val);
      },1);
    });
    res.subscribe(
      resposne => {
        this.rowData2 = resposne;
      });

      let res1 : Observable<any> = Observable.create(observer => {
      setTimeout(()=>{
        observer.next(val);
      },2000);
    });
    res1.subscribe(
      resposne => {
        this.rowData3 = resposne;
      });


    }
       /**
   * Select the first row as default...
   */
  public onRowDataChanged(): void {
    this.gridOptions.api.forEachNode(node => node.rowIndex ? 0 : node.setSelected(true));
  }


    private onReady(params) {
        params.api.sizeColumnsToFit();
       params.api.forEachNode(node => node.rowIndex ? 0 : node.setSelected(true));
    }
}

https://plnkr.co/edit/PSKnSjAo6omDAo5bjm1J

添加了带有三个 ag 网格的 plunker。 第一个网格具有预定义的 rowdata 值,第二个网格的 rowdata 是从 Observable 填充的,但延迟非常少,第三个网格的行数据值是从具有更高延迟的 observable 填充的。 在第一个和第二个“onGridReady”函数被调用并选择第一行的情况下,但在第三个网格的情况下,我们必须为要选择的行的“rowDataChanged”事件提供选择行语句。

在 onGridReady 上,您可以使用此代码默认选择第一行。

let  rowIndex = 0;
this.GridOptions.api.paginationGoToFirstPage(); // If pagination is implemented
this.GridOptions.api.selectIndex(rowIndex, false, false);
this.GridOptions.api.setFocusedCell(0, "FirstName");

尝试使用 gridOptions.api.setFocusedCell(0, [column name]) 其中列名可以是 ne 可见列

aggrid on ready 功能不适用于此交易。 agon ready 只是绘制表格,如果你想操作数据,你必须在 ag 准备好之前接近。 但是没有这个选项。如果你在你的方法中添加这个代码。

getProducts: async function() {
      let data = await repository.getAll("Product").then(r => r.list);
      for (let i = 0; i < this.value.length; i++) {
        for (let j = 0; j < data.length; j++) {
          if (this.value[i].productId == data[j].productId) {
            let x = data.splice(j, 1)[0];
            data.unshift(x);
            break;
          }
        }
      }
      this.productDataForAggrid = data;
      this.gridApi.setRowData(this.productDataForAggrid);
      window.watcher = setInterval(this.setSelectedItems, 50, this.gridApi);
    }

这个函数除了最后一部分是普通的get方法。 如果您在 ag 上选择了一些行,并且如果您关闭 ag,所有选择都将在表上删除,但是当您再次打开 ag 时,您仍然会在数据属性上选择哪些数据。 你会以这种方式休耕。这部分代码用于真正的就绪功能,我的意思是在准备数据之前。

setSelectedItems(api) {
      if (this.productDataForAggrid.length == api.getDisplayedRowCount()) {
        for (let i = 0; i < this.value.length; i++) {
          let node = api.getRowNode(this.value[i].productId.toString());
          if (node) {
            node.setSelected(true);
          }
        }
        this.gridApi.sizeColumnsToFit();
        clearInterval(window.watcher);
        window.watcher = 0;
        //console.log("ready!");
      }
    }

首先,我们将在 value prop 上添加所有选定的数据以添加到帐单列表中。 但是如果客户想重新打开产品选择aggrid 客户无法看到所选的产品。 这个 getproducts func 在每次 ag 打开时都有效。 并获得所有产品。 将此数据与我们的 value 属性进行比较。 并发送到 setSelectedItems 函数以进行检查选择。


 saveSelectedProducts() {
      this.value.splice(0, this.value.length);
      for (var i = 0; i < this.gridOptions.api.getSelectedRows().length; i++) {
        if (this.gridOptions.api.getSelectedRows()[i].sellPrice === undefined)
          this.gridOptions.api.getSelectedRows()[
            i
          ].sellPrice = this.gridOptions.api.getSelectedRows()[i].odooId;

        if (this.gridOptions.api.getSelectedRows()[i].piece === undefined)
          this.gridOptions.api.getSelectedRows()[i].piece = 1;

        this.value.push(this.gridOptions.api.getSelectedRows()[i]);
      }
      //this.$emit("selectedProductsList", this.value);
      this.openProductPopup = false;
    },

我们需要调用setSelected(true)方法来选择行节点。 主要问题是获取行节点。

我们可以通过调用getRenderedNodes()方法来获取行节点。 根据文档

检索渲染节点。 由于虚拟化,这将只包含当前可见的行和缓冲区中的行。

因此,我们将在getRenderedNodes()方法返回的数组的索引0处获取第一行节点。 实施将如下 -

public onGridReady(event: any): void {
  let nodes = event.api.getRenderedNodes();
  if (nodes.length) {
    nodes[0].setSelected(true); //selects the first row in the rendered view
  }
}

这是工作 plunker 演示: https ://plnkr.co/edit/J40sUeDSwyDEi76X

setSelected(false) 可以在 (selectionChanged) 事件上调用。

ag 网格公共方法上可用的网格事件之一

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM