Building a User Management Grid in Angular
A User Management Grid is a powerful tool often used in administrative dashboards to manage user data. It allows administrators to view, edit, and manage user records in an organized, scalable way. Building a user management grid in Angular can provide your application with dynamic functionality for managing users effectively.
In this blog, we will guide you step by step on how to build a User Management Grid in Angular. We will cover everything from setting up the environment, designing the grid, adding CRUD operations, and implementing search and pagination features to enhance user experience.
Step 1: Setting Up Your Angular Project
Before we start building the User Management Grid, ensure that your Angular development environment is set up.
1.1 Install Node.js and Angular CLI
If you haven’t already, install Node.js and npm (Node Package Manager) on your system. After that, install Angular CLI globally:
npm install -g @angular/cli
1.2 Create a New Angular Project
Create a new Angular project using the following command:
ng new user-management-grid
cd user-management-grid
1.3 Serve the Application
Serve the project locally:
ng serve
You can now visit http://localhost:4200
in your browser to check the default Angular app running.
Step 2: Installing Angular Material
To design an elegant, user-friendly grid, Angular Material is a great option. Angular Material provides a set of high-quality UI components, including tables, form fields, buttons, and more, which will help us design a responsive and interactive user grid.
2.1 Install Angular Material
Run the following command to install Angular Material, Angular CDK, and Angular Animations:
ng add @angular/material
Choose a theme and set up global typography and animations as needed. Angular Material will also update your angular.json
file to include the necessary styles and animations.
2.2 Import Angular Material Components
Next, import the Angular Material modules that we’ll need, such as MatTableModule
, MatPaginatorModule
, and MatSortModule
.
In your app.module.ts
, import the following Angular Material modules:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatSortModule } from '@angular/material/sort';
import { MatButtonModule } from '@angular/material/button';
import { MatDialogModule } from '@angular/material/dialog';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
MatTableModule,
MatPaginatorModule,
MatSortModule,
MatButtonModule,
MatDialogModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
Step 3: Designing the User Management Grid
We’ll now create the basic structure of our User Management Grid using MatTable
from Angular Material.
3.1 Create the User Table
In your app.component.html
, use Angular Material’s mat-table
to create a grid for displaying user data:
<mat-table [dataSource]="dataSource" matSort> <ng-container matColumnDef="id"> <mat-header-cell *matHeaderCellDef mat-sort-header> ID </mat-header-cell> <mat-cell *matCellDef="let user">{{ user.id }}</mat-cell> </ng-container> <ng-container matColumnDef="name"> <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell> <mat-cell *matCellDef="let user">{{ user.name }}</mat-cell> </ng-container> <ng-container matColumnDef="email"> <mat-header-cell *matHeaderCellDef mat-sort-header> Email </mat-header-cell> <mat-cell *matCellDef="let user">{{ user.email }}</mat-cell> </ng-container> <ng-container matColumnDef="actions"> <mat-header-cell *matHeaderCellDef> Actions </mat-header-cell> <mat-cell *matCellDef="let user"> <button mat-button (click)="editUser(user)">Edit</button> <button mat-button (click)="deleteUser(user)">Delete</button> </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row> <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row> </mat-table> <mat-paginator [length]="data.length" [pageSize]="5" [pageSizeOptions]="[5, 10, 20]"></mat-paginator>
3.2 Define Columns in TypeScript
In the app.component.ts
, define the columns and data for the user grid:
import { Component, OnInit, ViewChild } from '@angular/core'; import { MatTableDataSource } from '@angular/material/table'; import { MatPaginator } from '@angular/material/paginator'; import { MatSort } from '@angular/material/sort'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { displayedColumns: string[] = ['id', 'name', 'email', 'actions']; dataSource: MatTableDataSource<any>; data = [ { id: 1, name: 'John Doe', email: 'john@example.com' }, { id: 2, name: 'Jane Smith', email: 'jane@example.com' }, { id: 3, name: 'Mark Johnson', email: 'mark@example.com' }, // Add more sample users here ]; @ViewChild(MatPaginator) paginator: MatPaginator; @ViewChild(MatSort) sort: MatSort; ngOnInit() { this.dataSource = new MatTableDataSource(this.data); this.dataSource.paginator = this.paginator; this.dataSource.sort = this.sort; } editUser(user: any) { console.log('Edit user:', user); } deleteUser(user: any) { console.log('Delete user:', user); } }
Step 4: Adding CRUD Operations
Now, let’s add the Create, Read, Update, and Delete (CRUD) operations to manage the users dynamically.
4.1 Create and Edit User
Create an Edit User Dialog component where you can edit user details.
ng generate component edit-user-dialog
edit-user-dialog.component.html
, create a form for editing user details:<h2 mat-dialog-title>Edit User</h2> <mat-dialog-content> <mat-form-field> <mat-label>Name</mat-label> <input matInput [(ngModel)]="user.name" /> </mat-form-field> <mat-form-field> <mat-label>Email</mat-label> <input matInput [(ngModel)]="user.email" /> </mat-form-field> </mat-dialog-content> <mat-dialog-actions> <button mat-button (click)="closeDialog()">Cancel</button> <button mat-button (click)="saveUser()">Save</button> </mat-dialog-actions>
edit-user-dialog.component.ts
, handle the saving logic:import { Component, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; @Component({ selector: 'app-edit-user-dialog', templateUrl: './edit-user-dialog.component.html', styleUrls: ['./edit-user-dialog.component.css'] }) export class EditUserDialogComponent { user: any; constructor( public dialogRef: MatDialogRef<EditUserDialogComponent>, @Inject(MAT_DIALOG_DATA) public data: any ) { this.user = { ...data }; // Clone the user data } closeDialog(): void { this.dialogRef.close(); } saveUser(): void { this.dialogRef.close(this.user); } }
app.component.ts
to open the edit form and save changes:import { MatDialog } from '@angular/material/dialog';
import { EditUserDialogComponent } from './edit-user-dialog/edit-user-dialog.component';
// Inject MatDialog in the constructor
constructor(public dialog: MatDialog) {}
editUser(user: any): void {
const dialogRef = this.dialog.open(EditUserDialogComponent, {
width: '300px',
data: user
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
const index = this.data.findIndex(u => u.id === result.id);
if (index !== -1) {
this.data[index] = result;
this.dataSource.data = this.data; // Refresh data
}
}
});
}
4.2 Delete User
Add the delete logic inside the deleteUser
method:
deleteUser(user: any): void {
const index = this.data.findIndex(u => u.id === user.id);
if (index !== -1) {
this.data.splice(index, 1);
this.dataSource.data = this.data; // Refresh data
}
}
Conclusion
With the above steps, you’ve successfully created a User Management Grid in Angular, which allows you to display user data, sort, paginate, and perform CRUD operations like editing and deleting users. The Angular Material components such as mat-table
, mat-paginator
, and mat-dialog
offer a sleek, responsive UI that improves the user experience. Additionally, by using services and Angular’s built-in data handling capabilities, your app is well-prepared for scalability and future enhancements.
By following this guide, you can easily extend this grid to suit your specific application needs, whether by adding more advanced features like search functionality, user filtering, or integrating with a backend API for persistent data storage.