Setting up ag-Grid without displaying an empty grid at the start

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?

Answer №1

There are certain pages where I prefer not to display the grid until it has been populated. To achieve this, I utilize a boolean variable named showGrid, initially set to false.

If you update your code:

*ngIf="rowData.length > 0"

to

*ngIf="showGrid"

Simply switch showGrid to true within the code when you are ready to view the grid.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a dynamic HTML component with Angular

I am tasked with developing two separate themes for an angular application. These themes should be loaded based on a property retrieved from an API call. I plan to create two HTML files that will share the same .ts code, since the core functionality will n ...

Encountered an issue with running tests in vscode-test - runTests function throwing

Setting up tests for my vscode extension for the first time and encountering an issue. I copied and pasted the example from code.visualstudio's /working-with-extensions/testing-extension. However, I'm facing an error when trying to call runTest ...

Adding Dynamic Checkboxes to Angular Forms in Angular 4

Currently, I am in the process of working on an angular 4 form using Angular forms. I am looking for a way to dynamically add an input (checkbox) to the formArray after constructing the form. Here is the TypeScript code snippet: signes_p = [ { id: &apo ...

Issues with the functionality of multiselect in Angular2-PrimeNg's reactive forms are currently being experienced

Currently, I am utilizing PrimeNG version 2.0.3 alongside Angular 2.0.0 while implementing reactive forms. My aim is to incorporate the multiselect functionality of PrimeNg into my form. To achieve this, I have taken the following steps: Component.html ...

Tips on retrieving enum values in typescript

Having trouble retrieving values from an enum? Check out this snippet of code: export const enum ComplianceType { ENGINEER_ASSESMENT = 'ENGINEER_ASSESMENT', CONSTRUCTION_COMPLIANCE = 'CONSTRUCTION_COMPLIANCE', ARCHITECTURE_ASSIGN ...

Tips for centering text inside a div using a separator

During my side project, I decided to use the angular material divider but encountered issues with aligning the text correctly. https://i.stack.imgur.com/zg1mu.png The problem can be seen in the image provided - the text on the right side is not aligned b ...

Visual Studio Code unable to locate source maps for typescript debugging

Looking for some help debugging a basic Hello World TypeScript file. Whenever I try to set a breakpoint, it seems like VS Code is having trouble locating the source map, even though it's saved in the same directory. I'm using Chrome as my browser ...

Error: `target` property is not recognized on `htmlelement` type

I am attempting to retrieve the ID of a list item in a select menu but I am having trouble getting the value from it. The value should be a number. HTML File <div class="form-group mt-3"> <label class="form-label">Produc ...

Tips for retrieving array data from a Node API to utilize in an Angular *ngFor loop

I've encountered an issue while using data from a node API (mongoDB collection) in an Angular *ngFor loop. The error message indicates that the data needs to be in array format for *ngFor to work properly. When I check the console log output of the A ...

Take a look at the browser's view

Are there any methods to monitor changes in the browser window using an Observable, such as rxJS or a similar tool? I am interested in triggering an action whenever the browser window is resized. ...

What is the best way to fully reload an Angular component when the route is changed?

I'm looking for a way to reload or refresh a sidebar component when the route changes. Below is the code I currently have: constructor( private auth: AuthService, private router: Router, private changeDetector: ChangeDetectorRef ) { ...

Integrating Typescript with React Redux-Thunk

Currently, I am attempting to type my Redux Actions using Redux Thunk Below is an example of one Action: export function logout() { return async(dispatch) => { try { const value = localStorage.removeItem("token"); dispatch(cons.upda ...

Exploring TypeORM: Leveraging the In() function within @ManyToMany relationships

There are two main characters in my story: Hero and Villain (their profiles are provided below). How can I utilize the Encounter() method to identify all instances where the Hero interacts with the Villain based on an array of Villain IDs? I am seeking a ...

How can I toggle the display of a div within an li when clicked?

My issue involves using ngFor for li elements, each having a click event. My goal is to toggle the visibility of a div within the li when clicked. Any suggestions on how I can achieve this? Each li contains a unique ptechnologyName. <li *ngFor="let bil ...

Is there a way to revert my Ionic CLI back to the previous version that I had installed?

Having just updated to version 3.2.0, I am encountering numerous issues, such as the malfunctioning of the ionic serve command. ...

Effect fails to activate on the third occurrence of the action

After successfully running on the first two action dispatches, the effects fail to trigger on the third time. I have tried the solutions provided in this thread and here, but none of them work for me. Here is the relevant code snippet: @Effect() get ...

What is the best method to monitor HTTP errors when making multiple API calls?

Can someone guide me on how to handle http-errors when making repeated API calls? I've been experimenting with loading mock images from lorempicsum and I want to properly catch any http-errors that may occur. I attempted to use rxjs catchError() wit ...

learning how to transfer a value between two different components in React

I have 2 components. First: component.ts @Component({ selector: "ns-app", templateUrl: "app.component.html", }) export class AppComponent implements OnInit { myid: any; myappurl: any; constructor(private router: Router, private auth: ...

Angular 2 Component does not belong to any specific NgModule

I'm currently in the process of upgrading my Angular 2 project from RC5 to version 2.0.0, but I encountered an error: Unhandled Promise rejection: Component LoginComponent is not part of any NgModule or the module has not been imported into your mo ...

Compilation error in Angular 7 development process

Using Angular 7, npm 5.5.1 and node 8.9.0 In the terminal... npm run build:test <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5435252503736d736d73">[email protected]</a> build:test C:\Projects\fff ng ...