typescript 如何获取angular2中ag网格中选中行的数据?

bnl4lu3b  于 2023-02-10  发布在  TypeScript
关注(0)|答案(8)|浏览(189)

我已经在angular2中设置了ag-grid,它工作正常,但是我无法获得所选行的值......在我的控制台窗口中没有错误......这就是我初始化网格的方式......

import {Component} from 'angular2/core';

@Component({
selector: 'aggride',
template: `

<div class="tr-card" >
<ag-grid-ng2  #agGrid of mgrid   class="ag-fresh"   rowHeight="40px"    
               [columnDefs]="columnDefs" 
                [rowData] = "rowData"
     enableCellExpressions="true"  
 enableSorting="true"  
  unSortIcon="true"
rowSelection="single"
(getSelectedRows) = "getSelectedRows()"
(onSelectionChanged) = "onSelectionChanged()"
>
</ag-grid-ng2>
</div>
`,
directives: [(<any>window).ag.grid.AgGridNg2],
})

这是类中用于获取选定值的代码

export class AgGride {
gridOptions = {
    columnDefs: 'columnDefs',
    rowData: 'rowData',
    rowSelection: 'single',
    getSelectedRows: 'getSelectedRows',
    onSelectionChanged: 'onSelectionChanged'
};

columnDefs = [
    { headerName: "Make", field: "make", editable: true },
    { headerName: "Model", field: "model", editable: true },
    { headerName: "Color", field: "Color", editable: true }
];

rowData = [
    { make: "Toyota", model: "Celica", Color: "Red"},
    { make: "Ford", model: "Mondeo", Color: "Blue"},
    { make: "Tata", model: "X100", Color: "Blue"},
    { make: "Volvo", model: "X5", Color: "White"},      
];

mgrid: any;
onSelectionChanged() {
    var selectedRows = this.mgrid.ag.this.gridOptions.getSelectedRows();
    console.log(selectedRows);

}
}

有人请告诉我如何才能纠正我的错误,以便我会得到我的控制台窗口中选定行的数据/值...

mf98qq94

mf98qq941#

在模板上,例如:

(rowClicked)='onRowClicked($event)'
(cellClicked)='onCellClicked($event)'
(selectionChanged) = 'onSelectionChanged($event)'

然后是组件类:

onRowClicked(event: any) { console.log('row', event); }
onCellClicked(event: any) { console.log('cell', event); }
onSelectionChanged(event: any) { console.log("selection", event); }

使用Chrome控制台检查事件对象内容。

ddrv8njm

ddrv8njm2#

你可以使用API()返回一个选定行数据的数组.

public getSelectedRows(){
        let rowsSelection = this.gridOptions.api.getSelectedRows();
        console.info(rowsSelection);
      }

这对我很有效

ux6nzvsh

ux6nzvsh3#

在HTML中,将rowClicked事件绑定到您自己的函数,如下所示。

<ag-grid-angular #grid
      style="width: 100%; height: 500px;" class="ag-theme-balham"
      [rowData]="rowList" [columnDefs]="columnsList" [rowSelection]="selectionMode"
      (rowClicked)="onRowClick($event)"
    >
    </ag-grid-angular>

然后在TS或JS中使用如下API

onRowClick(event) {
    if (this.selectionMode === 'multiple') {
      this.selectedEntity = this.grid.api.getSelectedRows();
    } else {
      this.selectedEntity = this.grid.api.getSelectedRows()[0];
    }
}

当你的网格有多重选择这样的功能时,所有选中的数据都不会通过event参数,它总是只会是选中的行。
我不鼓励selectionChanged事件的原因是,它总是在selectionChanged事件之前调用rowClicked事件。

dffbzjpn

dffbzjpn4#

如果使用onSelectionChanged(),则可以使用api.getSelectedRows()onSelectionChanged函数获取选定数据。

selectedRow: any;
canceLDateAGGrid() {
    this.dateGridOptions = {
        columnDefs: [{
            headerName: this.Label[0].GEN_ORG_lblName,
            field: 'DependantName',
            width: 200,
            filter: 'agTextColumnFilter'
        }, ],
        showRowSelection: true,
        checkboxSelection: false,
        onSelectionChanged: (event) = > this.onSelectionChanged(event),
    };
}
onSelectionChanged(event) {
    let selectdata = event.api.getSelectedNodes();
    this.selectedRow = event.api.getSelectedRows();
    console.log(this.selectedRow)
}
q5lcpyga

q5lcpyga5#

首先,必须通过将gridOptions.rowSelection设置为"single""mulitple"来启用行选择,具体取决于您希望实现的选择行为。
然后,您可以使用网格API方法getSelectedNodes()返回ag-Grid中所有当前选定行的列表。从每个节点提取数据非常简单,只需Map到每个节点并返回其data属性即可。
下面是使用JavaScript框架时的代码:

getSelectedRowData() {
    let selectedNodes = this.gridApi.getSelectedNodes();
    let selectedData = selectedNodes.map(node => node.data);
    alert(`Selected Nodes:\n${JSON.stringify(selectedData)}`);
    return selectedData;
}

您还可以在下面的Angular/React/Vue.js示例中看到这一点:
Angular
React
Vue.js
Vanilla JS

  • 注意:使用Vanilla JS时,可以从gridOptions对象访问gridApi和columnApi。*

阅读我们的blog上的完整帖子或查看我们的documentation,了解可以使用ag-Grid实现的各种场景。
艾哈迈德·加迪尔|开发人员@ ag-Grid

jutyujz0

jutyujz06#

onRowSelected: params => {
  const selectedRows = params.api.getSelectedRows();
  console.log(selectedRows);
}
ghhkc1vu

ghhkc1vu7#

import { HttpClient } from '@angular/common/http';
    import { parseI18nMeta } from '@angular/compiler/src/render3/view/i18n/meta';
    import { Component } from '@angular/core';
    import { ColDef, GridReadyEvent, ICellRendererParams } from 'ag-grid-community';
    import { Observable } from 'rxjs';
    import { MyCellComponent, MyCellParams } from './my-cell/my-cell.component';
    import { OverComponent } from './over/over.component';
    import { RemoveButtonComponent } from './remove-button/remove-button.component';
    import { UnderComponent } from './under/under.component';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
      public columnDefs: ColDef[] = [
        {
          field: 'athlete',
          cellRenderer: MyCellComponent,
          cellRendererParams: {
            buttonText: 'Name',
          } as MyCellParams
        },
        {
          field: 'age',
          cellRendererSelector: (params: ICellRendererParams) => {
            if (params.value < 25) {
              return { component: UnderComponent, params: {} };
            }
            return { component: OverComponent }
          }
        },
        {
          field: 'country',
          cellRenderer: (params: ICellRendererParams) => {
            return `<b> !! ${params.value} </b>`
          }
        },
        { field: 'year' },
        { field: 'sport' },
        { field: 'gold' },
        { field: 'silver' },
        { field: 'bronze' },
        { field: 'total' },
        {
          field: 'action',
          cellRenderer: RemoveButtonComponent,
          cellRendererParams: { context: this },
        },
      ];
      public defaultColDef: ColDef = {
        sortable: true,
        filter: true,
      };
    
      public rowData$!: Observable<any[]>;
      gridApi: any;
    
      constructor(private http: HttpClient) { }
    
      onGridReady(params: GridReadyEvent) {
        this.gridApi = params.api;
        this.rowData$ = this.http
          .get<any[]>('https://www.ag-grid.com/example-assets/olympic-winners.json');
        //params.columnApi.autoSizeAllColumns()
      }
      onRemoveClick(data: any) {
        console.log(data, "data")
      }
      onClick() {
        alert("hi")
      }
    }

**//Remove Component**

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-remove-button',
  template: `<button (click)="clickHandler(rowData)">Remove</button>`,
  styles: [
  ]
})
export class RemoveButtonComponent implements OnInit {

  constructor() { }
  public rowData: any;
  private params: any;

  public agInit(params: { data: any, context: any }) {
    this.rowData= params.data;
    this.params = params;
  };

  public clickHandler(data: any) {
    this.params.context.onRemoveClick(data);
  }
  ngOnInit(): void {
  }

}
23c0lvtd

23c0lvtd8#

问题似乎出在gridOptions属性的访问上。要访问网格选项,可以使用组件模板中的ag-grid-ng2组件引用。
请尝试以下代码:

export class AgGride {
      columnDefs = [
        { headerName: "Make", field: "make", editable: true },
        { headerName: "Model", field: "model", editable: true },
        { headerName: "Color", field: "Color", editable: true }
      ];
    
      rowData = [
        { make: "Toyota", model: "Celica", Color: "Red"},
        { make: "Ford", model: "Mondeo", Color: "Blue"},
        { make: "Tata", model: "X100", Color: "Blue"},
        { make: "Volvo", model: "X5", Color: "White"},      
      ];
    
      @ViewChild("agGrid") agGrid: any;
    
      onSelectionChanged() {
        var selectedRows = this.agGrid.api.getSelectedRows();
        console.log(selectedRows);
      }
    }

这里,@ViewChild装饰器用于获取对ag-grid-ng2组件的引用,然后,您可以使用this.agGrid.api访问网格API,并使用this.agGrid.api.getSelectedRows()获取所选的行。

相关问题