Table of Contents
Overview-
- This blog covers how to remove an item in grid in Angular using step-by-step instructions
- It shows you how to set up an Angular grid, remove items as needed, and add confirmation pop-ups to keep users safe.
- Also learn how to handle complex data and use Angular’s change detection to make sure your grid works smoothly
Girds are required to display tabular data in an organized and user-friendly way in most Angular applications. Managing the items dynamically within these grids is a common requirement. This blog will guide you through how to remove an item in grid in Angular, using an Angular Material table (MatTable) or similar components. You can hire dedicated angular developers and greatly benefit your project by providing expertise in implementing efficient data management, user-friendly interactions, and scalable web applications.
Setting Up the Angular Grid Component
Before learning how to remove an item in grid in Angular, it’s crucial to understand how to set up the grid component. First, initialize your Angular project and set up the grid, which can use Angular Material’s MatTable or a simple HTML table. The structure contains three key columns: ID, Employee Name, and Role, each with a “Remove” button.
HTML Template (grid.component.html)
<table mat-table [dataSource]="dataSource" class="mat-class">
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef> ID </th>
<td mat-cell *matCellDef="let DataList"> {{DataList.id}} </td>
</ng-container>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> Employee Name </th>
<td mat-cell *matCellDef="let DataList"> {{DataList.name}} </td>
</ng-container>
<ng-container matColumnDef="action">
<th mat-header-cell *matHeaderCellDef> Role</th>
<td mat-cell *matCellDef="let DataList">
<button mat-button (click)="removeItem(DataList.id)">Remove</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
Users can interact and remove items dynamically from the grid as this layout creates a user-friendly interface.
Defining the Data and Methods in Your Component
After setting up the grid, the next step is to define the data and the method for item removal in the component class. In Angular, data binding ensures smooth communication between the component and the template.
TypeScript (grid.component.ts)
import { Component } from '@angular/core';
@Component({
selector: 'app-grid',
templateUrl: './grid.component.html',
styleUrls: ['./grid.component.css'],
})
export class GridComponent {
// Sample data for the grid
dataSource = [
{ id: 331, name: 'Employee 1' },
{ id: 332, name: 'Employee 2' },
{ id: 333, name: 'Employee 3' },
];
displayedColumns: string[] = ['id', 'name', 'role'];
// Method to remove an item from the grid
removeItem(id: number) {
const indx = this.dataSource.findIndex((item) => item.id === id);
if (indx >= 0) {
this.dataSource.splice(indx, 1); // Remove item from array
this.dataSource = [...this.dataSource]; // Re-assign to trigger change detection
}
}
}
In this code:
- Data Source Array: Holds the grid’s data, where each object contains id and name.
- Displayed Columns: Defines which columns to display.
- Remove Item: Removes an item when a user clicks “Remove”.
If you ever encounter module loading issues, such as with Angular’s Full-calendar module, this approach ensures that the removal process is handled efficiently.
Ensuring Angular Change Detection
One important aspect of removing items in Angular is ensuring that the framework detects changes in the dataSource. This is achieved by reassigning the dataSource to a new array after an item is removed.
this.dataSource = […this.dataSource];
By doing this, Angular detects the changes and updates the grid in real time. This technique ensures your app handles complex scenarios like copying a string programmatically or integrating advanced data interactions seamlessly.
Adding Confirmation Before Removal (Optional)
In most applications, removing items is a critical action. To avoid accidental deletions, you can add a confirmation dialog using Angular Material’s MatDialog.
First, install Angular Material if it’s not already part of your project:
ng add @angular/material
HTML Template Update (grid.component.html)
<button mat-button (click)=”openConfirmationDialog(DataList.id)”>Remove</button>
In this updated template, clicking the “Remove” button now triggers a confirmation dialog.
Removing an Item with Confirmation (Code Walkthrough)
Let’s walk through the code for implementing a confirmation dialog before removing an item:
TypeScript (grid.component.ts)
import { MatDialog } from '@angular/material/dialog';
import { Component } from '@angular/core';
@Component({
selector: 'app-grid',
templateUrl: './grid.component.html',
styleUrls: ['./grid.component.css'],
})
export class GridComponent {
dataSource = [
{ id: 331, name: 'Employee 1' },
{ id: 332, name: 'Employee 2' },
{ id: 333, name: 'Employee 3' },
];
displayedColumns: string[] = ['id', 'name', 'role'];
constructor(private dialog: MatDialog) {}
removeItem(id: number) {
const indx = this.dataSource.findIndex((item) => item.id === id);
if (indx >= 0) {
this.dataSource.splice(indx, 1);
this.dataSource = [...this.dataSource];
}
}
openConfirmationDialog(id: number) {
const dRef = this.dialog.open(ConfirmDialogComponent);
dRef.afterClosed().subscribe((result) => {
if (result) {
this.removeItem(id); // Only remove if the user confirmed
}
});
}
}
@Component({
selector: 'app-confirmation-dialog',
template: `
<h2 mat-dialog-title>Confirm Removal</h2>
<mat-dialog-actions>
<button mat-button (click)="dRef.close(true)">Yes</button>
<button mat-button (click)="dRef.close(false)">No</button>
</mat-dialog-actions>
`,
})
export class ConfirmDialogComponent {
constructor(public dRef: MatDialog) {}
}
Conclusion
In this blog, we covered how to remove an item in grid in Angular, step by step. From setting up the Angular grid component, and defining the data source, to implementing the removal function with optional confirmation, this guide provides everything you need to manage grid items dynamically. Whether you’re working with simple arrays or external APIs, Angular offers a flexible and powerful framework for managing grids in your applications. At Soft Suave we offer complete web app development services and are ready to help you meet your unique project requirements.