
This blog post provides a comprehensive guide on how to implement an Angular Material table with sorting and API data fetching. It covers the installation of necessary packages, module and component creation, data source setup, and sorting functionality, ensuring a complete understanding of the process.
In this blog post, we will explore how to implement an Angular Material table in your project, complete with sorting and data fetching from an API. This guide is particularly useful if you have multiple tables in your application and prefer to use a library rather than creating a custom implementation from scratch.
Angular Material is a library supported by the Angular team, ensuring compatibility and scalability. It provides a robust solution for creating tables and other UI components without the need for extensive custom coding.
To begin, we need to install Angular Material and Angular CDK. Open your console and run the following commands:
yarn add @angular/material
yarn add @angular/cdk
Make sure to check your Angular version to ensure compatibility. For example, if you are using Angular version 14, both Angular Material and CDK should also be version 14.
Next, we will create a new module to isolate our table. In your project, create a new module called UsersTableModule. Inside this module, we will create a file named users-table.module.ts and register the Angular module, importing the CommonModule.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { UsersTableComponent } from './users-table.component';
@NgModule({
declarations: [UsersTableComponent],
imports: [CommonModule],
exports: [UsersTableComponent]
})
export class UsersTableModule {}
Now, import the UsersTableModule into your main AppModule to render the component in your application.
import { UsersTableModule } from './users-table/users-table.module';
@NgModule({
imports: [BrowserAnimationsModule, UsersTableModule],
})
export class AppModule {}
Inside the UsersTableModule, create a new component called UsersTableComponent. This component will contain the HTML and TypeScript logic for our table.
import { Component } from '@angular/core';
@Component({
selector: 'app-users-table',
templateUrl: './users-table.component.html'
})
export class UsersTableComponent {}
In the users-table.component.html, we will define the structure of our table using Angular Material directives. We will create a table with columns for ID, Name, and Age.
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef> ID </th>
<td mat-cell *matCellDef="let element"> {{element.id}} </td>
</ng-container>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> Name </th>
<td mat-cell *matCellDef="let element"> {{element.name}} </td>
</ng-container>
<ng-container matColumnDef="age">
<th mat-header-cell *matHeaderCellDef> Age </th>
<td mat-cell *matCellDef="let element"> {{element.age}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
To fetch data from an API, we will create a data source. First, define an array of displayed columns in the component's TypeScript file.
export class UsersTableComponent implements OnInit {
displayedColumns: string[] = ['id', 'name', 'age'];
dataSource = []; // This will hold our data
ngOnInit() {
this.loadData();
}
loadData() {
// Fetch data from API
}
}
We will create a service to fetch user data from an API. Create a new service called UserService and implement a method to fetch users.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from './user.model';
@Injectable({ providedIn: 'root' })
export class UserService {
constructor(private http: HttpClient) {}
fetchUsers(): Observable<User[]> {
return this.http.get<User[]>('http://localhost:3004/users');
}
}
Inject the UserService into the UsersTableComponent and call the fetchUsers method to populate the data source.
constructor(private userService: UserService) {}
loadData() {
this.userService.fetchUsers().subscribe(data => {
this.dataSource = data;
});
}
To add sorting functionality, import the MatSortModule in your UsersTableModule and add the sorting directive to your table.
import { MatSortModule } from '@angular/material/sort';
@NgModule({
imports: [CommonModule, MatSortModule],
})
In your HTML, add the sorting directive:
<table mat-table [dataSource]="dataSource" matSort>
In your component, implement the sorting logic by creating a method that will be triggered when sorting changes.
sortData(sort: Sort) {
const data = this.dataSource.slice();
if (!sort.active || sort.direction === '') {
this.dataSource = data;
return;
}
this.dataSource = data.sort((a, b) => {
const isAsc = sort.direction === 'asc';
switch (sort.active) {
case 'id': return compare(a.id, b.id, isAsc);
case 'name': return compare(a.name, b.name, isAsc);
case 'age': return compare(a.age, b.age, isAsc);
default: return 0;
}
});
}
By following these steps, you have successfully implemented an Angular Material table with sorting and API data fetching. This approach allows for a clean and efficient way to manage data presentation in your Angular applications. If you want to explore more about custom implementations without libraries, consider checking out additional resources on Angular tables.
Paste a YouTube link and let Magica create the key takeaways.
Summarize another video