how to add conditional template on ag-grid - ag-grid

can I do a conditional template on the first column below?
for example:
If my row has score property and I want to hide the input when my score is above 70?
let columns = [
{ width: 30, suppressSorting: true, suppressMenu: true, template: '<input type="checkbox">' },
{ headerName: "Score", filter: 'number', valueGetter: (params : any) =>
params.data.traces ? (<Alert> params.data.traces[0]).severity : params.data.severity, width:70},
{ headerName: "Behaviour tags" },
{ headerName: "Host", field: "host_name" },
{ headerName: "Group Id", cellRenderer: 'group', width:140 },
{ headerName: "Comments",width:290 }
];

Use cellRenderer property in your column object
let columns = [{ width: 30, suppressSorting: true, suppressMenu: true,
cellRenderer: function (params) {
var display = 'block';
if (params.data.score > 70) {
display = 'none';
}
var html = '<input type="checkbox" style="display: ' + display + '">';
return html;
}
}]
In params.data you have all row data

Related

Ag-grid is taking a lot of time to display with multiple Cell Renderer and Value Getter

I have to render ag-grid table in dialog box.
My grid has multi cellRenderer, valueGetter and cellRendererParams in columnDefs.
Instead of converting server data to rowData and using field to render, I have used valueGetter to fetch the value from the server data like
valueGetter: 'data.screen1.graph.visible'.
My ag-grid with 13 columns and 150 rows is taking noticeable time to render.
Is it because of valueGetter that my table is taking time to render?
Below is my sample data:
private createColumnDefs() {
this.columnDefs = [{
headerName: 'Header1',
cellRenderer: (params) => {
return params.data.serverObject1.function === 'input' ? 'I' : 'O';
},
minWidth: 50,
width: 70,
}, {
headerName: 'Header2',
field: 'serverObject1.name',
minWidth: 60,
width: 80,
}, {
headerName: 'Header3',
field: 'value',
cellRenderer: 'valueFieldRenderer',
minWidth: 100,
width: 250,
}, {
headerName: 'Header4',
cellRenderer: 'checkBoxRenderer',
valueGetter: 'data.serverObject1.graph.visible',
cellRendererParams(params) {
return {
disabledVal : params.data.localArray.length > 0 || params.data.attribute1 !== null
};
},
minWidth: 70,
width: 70,
}, {
headerName: 'Header5',
cellRenderer: 'checkBoxRenderer',
valueGetter: 'data.serverObject1.archive',
cellRendererParams(params) {
return {
disabledVal : params.data.serverObject1.function === 'input'
};
},
minWidth: 70,
width: 70,
}, {
headerName: 'Header6',
cellRenderer: 'checkBoxRenderer',
valueGetter: 'data.serverObject1.alarm',
cellRendererParams(params) {
return {
disabledVal : !((params.data.serverObject1.function === 'output') && (params.data.serverObject1.type === 'bool'))
};
},
minWidth: 70,
width: 70,
},
{
headerName: 'Header7',
cellRenderer: 'textBoxRenderer',
valueGetter: 'data.serverObject1.active',
minWidth: 150,
width: 150,
},
{
headerName: 'Header8',
cellRenderer: 'textBoxRenderer',
valueGetter: 'data.serverObject1.inactive',
minWidth: 150,
width: 150,
},
{
headerName: 'Header11',
cellRenderer: 'textBoxRenderer',
valueGetter: (params) => params.data.text1,
minWidth: 150,
width: 150,
cellStyle: (params) => {
return (this.diagram === 'XYZ' &&
!(params.data.serverObject1.function === 'output' || params.data.serverObject1.type === 'string'
|| params.data.serverObject1.type === 'int')) ? {display: 'block'} : {display: 'none'};
}}
];
}
cell renderer:
#Component({
selector: 'app-check-box',
template:
`
<input type="checkbox" [(ngModel)]="params.value" [id]="getID(params)" class="primary small"
(change)="onChange($event)">
<label [for]="getID(params)" class="text-hide">hidden</label>
`,
styleUrls: ['./test.component.css']
})
// tslint:disable-next-line:component-class-suffix
export class CheckBoxRenderer implements AfterViewInit, ICellRendererAngularComp {
private params: ICellRendererParams;
constructor(private readonly translateService: TranslateService) { }
agInit(params: ICellRendererParams): void {
this.params = params;
}
public onChange(event) {
}
refresh(params: any): boolean {
return false;
}
public getID(params): string {
return params.column.colId + params.rowIndex;
}
afterGuiAttached(params?: IAfterGuiAttachedParams): void {
}
ngAfterViewInit(): void {
}
translate(key: string, params?: any): string {
return this.translateService.instant(key, params);
}
}
Should I consider converting to rowData to decrease loading time?

ag-grid data for detailCellRendererParams not displaying

I'm trying to add a nested grid inside an existing grid. I'm very new at this, and although I'm able to display the grid, I cannot seem to display the data. When I do console.log(params), I have all my data, but no matter what I try, I cannot display the data. I think the problem is with my getDetailRowData, and what I'm passing to the successCallback function. Any ideas?
this is my component ts file
import { Component, OnInit } from '#angular/core';
import { ReportService } from 'src/app/services/report.service';
import { Report } from 'src/app/models/report';
import { agThemeSgBootstrap } from "#sg-bootstrap/ag-grid";
import {GridOptions, Module} from 'ag-grid-community';
import { DatePipe } from '#angular/common';
#Component({
selector: 'app-report',
templateUrl: './report.component.html',
styleUrls: ['./report.component.scss']
})
export class ReportComponent implements OnInit {
apiUrl: any;
reports : Report[];
gridOptions: GridOptions;
dateValue = new Date();
maxDate = new Date();
private detailCellRendererParams;
private columnDefs;
// public modules: Module[] = AllModules;
constructor(private reportService : ReportService, private datePipe: DatePipe) {
this.columnDefs = [
{headerName: 'Report Name', field: 'reportName', cellRenderer: 'agGroupCellRenderer',
resizable: true,
valueGetter: params => { return `${params.data.reportName}.dat` }},
{headerName: 'Sent to FIS', field: 'sentToFis',resizable: false,
valueGetter: params => { return params.data.sentToFis === true ? "Yes" : "No" } },
{headerName: 'File Size', field: 'contentLength', resizable: true,
valueGetter: params => { return `${this.formatBytes(params.data.contentLength)}` }},
{headerName: 'Last Modified', field: 'lastModified', resizable: true,
valueGetter: params => { return this.datePipe.transform(params.data.lastModified, "yyyy-MM-dd HH:mm:ss") }},
];
this.detailCellRendererParams = {
detailGridOptions: {
columnDefs: [
{headerName: 'ADSL Path', field: 'adslPath', resizable: true,
valueGetter: params => { return params.data.adlsFullPath}},
{headerName: 'Version', field: 'version', resizable: true,
valueGetter: params => { return params.data.sentToFis}},
{headerName: 'Source', field: 'source', resizable: true,
valueGetter: params => { return params.data.adlsFullPath}},
],
},
getDetailRowData: function(params) {
params.successCallback(params.data.children);
console.log(params.data);
}
}
}
ngOnInit() {
this.callReportService(new Date())
}
reportDateChange(value: Date) {
let currentValue = this.datePipe.transform(this.dateValue, "yyyyMMdd")
let newSelectedValue = this.datePipe.transform(value, "yyyyMMdd")
if (currentValue != newSelectedValue) {
if (this.gridOptions.api) {
this.gridOptions.api.showLoadingOverlay();
}
this.callReportService(value)
this.dateValue = value;
}
}
callReportService(value: Date) {
this.reportService.getReportsForDate(value).subscribe(x=> {
this.reports = x;
this.gridOptions.api.sizeColumnsToFit();
})
}
ngAfterContentInit() {
let agOpt = { ...{
animateRows: true,
enableRangeSelection: true,
defaultColDef: {
editable: false,
enableValue: false,
enableRowGroup: false,
enablePivot: true,
filter: true,
sortable: true
},
statusBar: {
statusPanels: [{
statusPanel: 'agTotalRowCountComponent',
align: 'left'
},
{
statusPanel: 'agFilteredRowCountComponent'
},
{
statusPanel: 'agSelectedRowCountComponent'
},
{
statusPanel: 'agAggregationComponent'
},
],
}
}, ...agThemeSgBootstrap }
this.gridOptions = { ...this.gridOptions, ...agOpt }
}
onGridReady(params) {
params.api.setDomLayout("autoHeight");
params.api.sizeColumnsToFit();
}
onGridSizeChanged(params) {
params.api.sizeColumnsToFit();
}
ngAfterViewInit() {
this.dateValue = new Date()
}
formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
}
my html file
<div class="container-fluid">
<div class="col-xs-12 col-12 col-md-3 form-group row">
<label for="reportDate" class="col-form-label">Report Date:</label>
<div class="col-sm-4 col-md-7">
<input id="reportDate"
class="form-control"
#dp="bsDatepicker"
(bsValueChange)="reportDateChange($event)"
[maxDate]="maxDate"
bsDatepicker
[bsValue]="dateValue" [bsConfig]="{ isAnimated: true, adaptivePosition: true, dateInputFormat: 'YYYY-MM-DD', containerClass: 'theme-red' }"/>
</div>
</div>
<div class="row">
<div class="col">
<ag-grid-angular
style="width: 100%; height: 300px;"
class="ag-theme-sg-bootstrap"
[gridOptions]="gridOptions"
[masterDetail]="true"
[detailCellRendererParams]="detailCellRendererParams"
[rowData]="reports"
[columnDefs]="columnDefs"
(gridReady)="onGridReady($event)"
(gridSizeChanged)="onGridSizeChanged($event)">
</ag-grid-angular>
</div>
</div>
</div>

Bind ag-grid with array

I have an array with values array=[3,4].I have to display the ag-grid values if it matches with array values.This is what i tried so far:
Attached is the plunkr :https://plnkr.co/edit/fKrvfzFYjdLbTLjFkqpY?p=preview
var array=[3,4];
var columnDefs = [
{headerName: "Jobs",field: "job", width: 90},
{headerName: "Location", field: "loc", width: 120 },
{headerName: "Value", field: "value", width: 120 }];
var rowData =[{job:'Developer',loc:'X',value:1},
{job: 'Manager',loc:'Y',value:2},
{job: 'Musician',loc:'Z',value:3},
{job: 'Manager',loc:'A',value:4},
{job: 'Tester',loc:'B',value:5},
{job: 'DBA',loc:'C',value:6}
];
var gridOptions = {
defaultColDef: {
sortable: true
},
columnDefs: columnDefs,
animateRows: true,
enableRangeSelection: true,
rowData: rowData,
checkbox : true
};
How to display the grid when value field value matches with array values.
Here is a plunkr with a working example - https://plnkr.co/edit/xdwI0Tql9I5n71D4QSDy?p=preview
Add a custom cellRenderer function like so in the column definition of values column
{
headerName: "Value",
field: "value",
width: 120,
cellRenderer: params => array.includes(params.value) ? params.value : ''
}

Ag-Grid, React, Redux Filters Issue - can not set setFilterModel()

Here is my scenario,
I am making a onFetchEvents Redux Action call and getting all events and passing it as follows. rowData={this.props.events.data}
Everything works fine. Now I need to apply a filter, and this requires another call to the server.
I set enableServerSideFilter: true, so that when a filter applied, datagrid does not make a call on its own.
I monitor filter changes and call handleFilterChanged. I get the const filterModel = this.gridApi.getFilterModel(); and send it to rest endpoint.
Everything works fine but the datagrid does not remember the filter state.
I tried this.gridApi.setFilterModel(filterModel); but it gets me into infinite loop.
To make the long story short, how can I use filters with Redux so that I have full control also where should I use this.gridApi.setFilterModel()
Let me know if you need more clarification.
Thanks
/* eslint-disable */
import React, { Component, Fragment } from 'react';
import { connect } from 'react-redux';
import { AgGridReact } from 'ag-grid-react';
import { fetchEvents } from '#mc/duck/actions/AppActions';
import 'ag-grid-enterprise';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-balham-dark.css';
// import './customTheme.scss';
// col resizing pipe is not visibles
class DatagridPage extends Component {
constructor(props) {
super(props);
this.state = {
params: {
filterModel: {},
page: 1,
limit: 10,
},
gridOptions: {
enableServerSideFilter: true,
enableSorting: true,
enableColResize: true,
suppressMenuHide: true,
pagination: true,
animateRows: true,
onFilterChanged: this.handleFilterChanged,
onSortChanged: () => console.log('onSortChanged'),
columnDefs: [
{
headerName: 'id',
field: 'id',
headerClass: 'test',
checkboxSelection: true,
filter: 'agTextColumnFilter',
},
{
headerName: 'name',
field: 'name',
headerClass: 'test',
filter: 'agTextColumnFilter',
},
{
headerName: 'risk score',
field: 'risk_score',
headerClass: 'test',
filter: 'agTextColumnFilter',
},
{
headerName: 'urgency',
field: 'urgency',
headerClass: 'test',
filter: 'agTextColumnFilter',
},
{ headerName: 'type', field: 'type', headerClass: 'test', filter: 'agTextColumnFilter' },
{
headerName: 'artifacts',
field: 'artifacts',
headerClass: 'test',
filter: 'agTextColumnFilter',
},
{
headerName: 'created',
field: 'created',
headerClass: 'test',
filter: 'agTextColumnFilter',
},
{
headerName: 'updated',
field: 'updated',
headerClass: 'test',
filter: 'agTextColumnFilter',
},
{ headerName: 'due', field: 'due', headerClass: 'test', filter: 'agTextColumnFilter' },
{
headerName: 'owner',
field: 'owner',
headerClass: 'test',
filter: 'agTextColumnFilter',
},
{
headerName: 'status',
field: 'status',
headerClass: 'test',
filter: 'agTextColumnFilter',
},
{
headerName: 'description',
field: 'description',
headerClass: 'test',
filter: 'agTextColumnFilter',
},
],
},
};
}
componentDidMount() {
console.log('componentDidMount');
const { params } = this.state;
this.props.onFetchEvents(params);
}
onGridReady = params => {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
this.gridApi.sizeColumnsToFit();
console.log('onGridReady', this.gridApi.getFilterModel());
};
onPageSizeChanged(newPageSize) {
var value = document.getElementById('page-size').value;
const paramsCopy = { ...this.state.params };
paramsCopy.limit = Number(value);
paramsCopy.page = 1;
this.setState({ params: paramsCopy }, () => this.props.onFetchEvents(paramsCopy));
this.gridApi.paginationSetPageSize(Number(value));
}
handleFilterChanged = () => {
console.log('handleFilterChanged');
const filterModel = this.gridApi.getFilterModel();
const paramsCopy = { ...this.state.params, filterModel };
console.group('handleFilterChanged');
console.log('filterModel', filterModel);
console.log('state filterModel', this.state.params.filterModel);
if (!areEqualShallow(filterModel, this.state.params.filterModel)) {
this.gridApi.setFilterModel(filterModel);
this.setState({ params: paramsCopy }, () => this.props.onFetchEvents(paramsCopy));
}
console.groupEnd();
function areEqualShallow(a, b) {
for (var key in a) {
if (!(key in b) || a[key] !== b[key]) {
return false;
}
}
for (var key in b) {
if (!(key in a) || a[key] !== b[key]) {
return false;
}
}
return true;
}
// this.gridApi.setFilterModel(filterModel);
};
render() {
return (
<Fragment>
<div>
Page Size:
<select onChange={this.onPageSizeChanged.bind(this)} id="page-size">
<option value="10">10</option>
<option value="100">100</option>
<option value="500">500</option>
<option value="1000">1000</option>
</select>
</div>
<div
className="ag-theme-balham-dark"
style={{
height: '500px',
width: '100%',
}}
>
<AgGridReact
rowSelection="multiple"
gridOptions={this.state.gridOptions}
columnDefs={this.state.columnDefs}
rowData={this.props.events.data}
defaultColDef={this.state.defaultColDef}
onGridReady={this.onGridReady}
rowHeight={49}
/>
</div>
</Fragment>
);
}
}
const mapStateToProps = state => ({
events: state.app.events,
});
const mapDispatchToProps = {
onFetchEvents: params => fetchEvents(params),
};
export default connect(
mapStateToProps,
mapDispatchToProps,
)(DatagridPage);
In your column definition try setting the newRowsAction to "keep", e.g.
{
headerName: 'name',
field: 'name',
headerClass: 'test',
filter: 'agTextColumnFilter',
filterParams: {
newRowsAction: 'keep'
}
}
Or set it for all via defaultColDef, e.g.
gridOptions: {
defaultColDef: {
filterParams: {
newRowsAction: 'keep'
}
}
}

"No Row To Show" message is coming after data binding from Services

The "No Row To Show" message is showing in grid, but the grid one row of data.
I have a demoComponent.ts and html file.
please refer my below code
demoComponent.ts
import { GridOptions } from "ag-grid/main";
import { Service } from '../Services/service';
#Component({
.
templateUrl: 'demoComponent.html',
.
})
#Injectable()
export class demoComponent implements OnInit {
GridOptions: GridOptions;
GridColumnDefs: any[];
GridData: any[];
data1 : any[]
constructor(private Service: Servicee) {
}
ngOnInit() {
this.GridOptions = <GridOptions>{
enableFilter: false,
rowSelection: 'multiple',
enableSorting: true,
enableColResize: true,
singleClickEdit: true,
animateRows: true,
headerHeight: 50,
rowClass: 'rowClass'
};
Observable.forkJoin(
this.Service.methed1(this.id),
this.Service.methed1(this.id),
this.Service.methed1(this.id),
this.Service.methed1()
).subscribe(response => {
this.data1 = <any>response[0];
this.data2 = <any>response[1];
this.data3 = <any>response[2];
this.data4 = <any>response[3];
this.GridBind()
});
}
GridBind()
{
this.GridColumnDefs = [
{ headerName: "", field: "id", hide: true },
{ headerName: "Column1", field: "Column1", width: 70, editable: true, tooltipField: "release", headerTooltip: "Release" },
{ headerName: "Column2", field: "Column2", width: 80, editable: true, tooltipField: "Column2", headerTooltip: "Column2",
//cellEditorFramework: EstimatingSourceComponent
cellEditorFramework: EstimatingSourceComponent,
cellEditorParams: {
dropDownValue: this.data1,
}
},
{ headerName: "Column3", field: "Column3", width: 70, editable: true },
{ headerName: "Column4", field: "Column4", width: 70, editable: true },
];
this.GridData = [
{
id: 1, Column1: this.data1.value1, Column2: this.data1.value2, Column3: this.data1.value3, Column4: this.data1.value4
}
];
}
}
Then the demoComponent.html
<ag-grid-angular style="width: 100%; height: 350px;"
id="grid1"
class="ag-fresh"
[rowData]="GridData"
[columnDefs]="GridColumnDefs"
[gridOptions]="GridOptions">
</ag-grid-angular>
on rendering the one row is binded with the grid. but "No Row To Show" is showing.
Please correct my implementation , if it is wrong.
thanks in advance