In the context of an ag-grid, data will only appear if the grid contains some content.
//HTML file
<form [formGroup]="myForm" (ngSubmit)="search()" >
<button type="submit" class="btn btn-default">Search</button>
</form>
<div class="col-md-12" *ngIf="rowData.length > 0">
<ag-grid-angular #agGrid style="width: 100%; height: 330px;" class="ag-fresh"
[gridOptions]="gridOptions"
[columnDefs]="columnDefs"
[rowData]="rowData"
[datasource] = "dataSource"
enableColResize
enableSorting
enableFilter
rowSelection="single"
></ag-grid-angular>
</div>
Within the component, I have defined the grid options in the constructor and initialized the data source in the search method, which is called upon submitting the form.
constructor(private masterDataService:MasterDataService,private http: Http) {
this.myForm = new FormGroup({
});
this.gridOptions = <GridOptions>{
context:{},
rowModelType: 'pagination',
enableServerSideFilter: true,
paginationPageSize: 10,
rowData: this.rowData,
columnDefs: this.columnDefs,
onReady: () => {
this.gridOptions.api.sizeColumnsToFit();
}
};
}
search(){
let self = this;
let dataSource = {
paginationPageSize: 10,
getRows: (params: any) => {
let headers: Headers = new Headers();
headers.set("Content-Type", "application/json");
console.log("here dataSource")
this.formatReqData(params.startRow, params.endRow);
this.http.post(AppUtils.INCIDENT_SEARCH, this.myForm.value, {headers: headers}).subscribe(res=>{
self.gridOptions.api.setRowData(res.json().result.incidentHdr);
self.rowData = res.json().result.incidentHdr;
var rowsselfPage = self.rowData;
var lastRow = -1;
params.successCallback(rowsselfPage, res.json().result.totalRecords);
});
}
}
//this.gridOptions.datasource = dataSource;
this.gridOptions.api.setDatasource(dataSource);
}
Error Message :
caused by: Cannot read property 'setDatasource' of undefined
This error can be resolved by removing "*ngIf="rowData.length > 0" from the HTML after removal.
<div class="col-md-12">
<ag-grid-angular #agGrid style="width: 100%; height: 330px;" class="ag-fresh"
[gridOptions]="gridOptions"
[columnDefs]="columnDefs"
[rowData]="rowData"
[datasource] = "dataSource"
enableColResize
enableSorting
enableFilter
rowSelection="single"
></ag-grid-angular>
</div>
However, a new issue arises where the grid loads initially before the search action, which is unnecessary. How can I prevent the grid from loading empty initially while still achieving the desired functionality?