Conditional Grid rendering with the *ngIf directive
12 Aug 20253 minutes to read
When working with dynamic data sources, it is recommended to render the Syncfusion Angular Grid only when there is actual data to display. Displaying an empty Grid can clutter the user interface and may lead to confusion.
By utilizing Angular’s *ngIf directive, you can conditionally include or remove elements from the DOM based on a boolean expression. This allows you to render the Grid only when data is available, ensuring a cleaner and more intuitive user experience.
In the following example, a button is used to toggle the visibility of the Grid. The *ngIf
directive is applied to the Grid, allowing to shows or hides the Grid depending on whether 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));