Conditional Grid rendering with the *ngIf directive

17 Sep 20253 minutes to read

When working with dynamic data sources, it is best practice to render the Syncfusion Angular Grid only when actual data is present. Avoiding the display of an empty grid improves user interface clarity and reduces potential confusion.

Angular’s *ngIf directive conditionally adds or removes elements from the DOM based on a boolean expression. By applying *ngIf to the Grid component, you ensure that the grid only renders when appropriate data is available, resulting in a cleaner and more intuitive user experience.

The following example demonstrates toggling the grid’s visibility with a button and rendering the grid conditionally with the *ngIf directive. The grid appears only when data is available.

import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { GridModule, PageService } from '@syncfusion/ej2-angular-grids';
import { ButtonModule } from '@syncfusion/ej2-angular-buttons';
import { data } from './datasource';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [GridModule, CommonModule, ButtonModule],
  providers: [PageService],
  template: `
    <div>
      <button ejs-button cssClass="e-primary" (click)="toggleGrid()" style="margin:5px">
        
      </button>
    </div>

    <div *ngIf="data.length > 0; else noData">
      <ejs-grid [dataSource]="data" allowPaging="true">
        <e-columns>
          <e-column field="OrderID" headerText="Order ID" textAlign="Right" width="90"></e-column>
          <e-column field="CustomerID" headerText="Customer ID" width="120"></e-column>
          <e-column field="Freight" headerText="Freight" textAlign="Right" format="C2" width="90"></e-column>
          <e-column field="OrderDate" headerText="Order Date" textAlign="Right" format="yMd" width="120"></e-column>
        </e-columns>
      </ejs-grid>
    </div>

    <ng-template #noData>
      <div class="no-data-msg" style="color:red; text-align: center">
        <p>No records available</p>
        <p>Please check your data source or try again later.</p>
      </div>
    </ng-template>
  `,
})
export class AppComponent implements OnInit {
  public data: object[] = [];

  ngOnInit(): void {
    this.data = data;
  }

  toggleGrid(): void {
    this.data = this.data.length > 0 ? [] : data;
  }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));