我在 Angular 中试验 AG Grid,并立即面临挑战。
我想确保 AG Grid 显示唯一的行。
我应该遍历网格并删除重复的行还是检查网格中是否已经存在具有这些值的行?
我正在考虑使用 Set 来应对这个挑战。我希望能在代码中找到最有效的解决方案。
grid-test.component.html
<!-- Button to clear selection -->
<button (click)="clearSelection()">Clear Selection</button>
<!-- AG Grid Angular Component -->
<ag-grid-angular
style="width: 70%; height: 100%; display: block; margin-left: auto; margin-right: auto;"
class="ag-theme-alpine"
[columnDefs]="columnDefs"
[defaultColDef]="defaultColDef"
[rowData]="rowData$ | async"
[rowSelection]="'multiple'"
[animateRows]="true"
(gridReady)="onGridReady($event)"
(cellClicked)="onCellClicked($event)"
></ag-grid-angular>
网格测试.component.ts
import { HttpClient } from '@angular/common/http';
import { Component, OnInit, ViewChild } from '@angular/core';
import { AgGridAngular } from 'ag-grid-angular';
import { CellClickedEvent, ColDef, GridReadyEvent } from 'ag-grid-community';
import { Observable } from 'rxjs';
@Component({
selector: 'app-grid-test',
templateUrl: './grid-test.component.html',
styleUrls: ['./grid-test.component.css']
})
export class GridTestComponent implements OnInit {
ngOnInit(): void {
}
// Each Column Definition results in one Column.
public columnDefs: ColDef[] = [
{ field: 'make'},
{ field: 'model'},
{ field: 'price' }
];
// DefaultColDef sets props common to all Columns
public defaultColDef: ColDef = {
sortable: true,
filter: true,
};
// Data that gets displayed in the grid
public rowData$!: Observable<any[]>;
// For accessing the Grid's API
@ViewChild(AgGridAngular) agGrid!: AgGridAngular;
constructor(private http: HttpClient) {}
// Example load data from sever
onGridReady(params: GridReadyEvent) {
this.rowData$ = this.http
.get<any[]>('https://www.ag-grid.com/example-assets/row-data.json');
}
// Example of consuming Grid Event
onCellClicked( e: CellClickedEvent): void {
console.log('cellClicked', e);
}
// Example using Grid's API
clearSelection(): void {
this.agGrid.api.deselectAll();
}
}
您可以采取多种方法来确保没有具有相同数据的重复行。
一种方法是使用迭代每一行api.forEachNode
并跟踪是否已经存在一行。
另一种方法是从当前行数据创建一个 Set,然后将其转换回数组。您可以在以下 plunkr中看到一个正在实施的示例。
onBtnRemove() {
const rowDataSlash = new Set(
this.rowData.map((row) => row.make + '/' + row.model + '/' + row.price)
);
const newRowData = Array.from(rowDataSlash).map((row) => {
const rowParts = row.split('/');
return { make: rowParts[0], model: rowParts[1], price: rowParts[2] };
});
this.rowData = newRowData;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句