Angular Material Table With Node JS API (Learn it in 21 Steps)

Angular Material Table With Node JS API (Learn it in 21 Steps)

Please find the below steps to show the angular material table with node js API and apply the filter in angular application.

  1. Create an angular project with the below command.

ng new angular-material-table

2. After successful creation of the angular app, change the file directory to project-name. “cd angular-material-table”

Open the project in vs code using “code .” in terminal or open with vs code. Then run the project using “ng serve” in the terminal. Open project in chrome using ***localhost:4200***

3. Open the app component in vs code and remove the content which is created by angular CLI while creating the app.

For Adding angular material using the command

**ng add @angular/material**

4. Select theme, Am selecting Indigo/Pink, and click the below items as “yes

  • Set up global Angular Material typography styles? Am selecting y
  • Set up browser animations for Angular Material? (Y/n) Select ‘y’.

5. Created Shared Module in the libs folder using “ng generate module shared”. And import , export material modules in “shared.module.ts”. And also add in the app.module.ts

shared.module.ts

6. Create the Audits component in the apps/components folder. And add audits component in router and path as audits. Run the project by using “ng serve” and open the audits component by using “localhost:4200/audits” in the browser address bar.

7. Inside the audits.component.ts file create a variable for displaying columns as below and also create the total count variable.

public displayedColumns: any = ["uri",'email',"clientIp",'client_org',"serverIp",'server_org',"statusMessage","createdAt","updatedAt"]public totalCount=0;

8. For calling API request from audits.component.ts to get audit records created one method i.e. this.getAudits(0,10) and call this method from ngOnInit();

**public ngOnInit():void{
this.getAudits(0,5)
}
public getAudits(pageIndex,pageSize){

}**

9. Create the audit-service file in the app/apis folder by using the below command. Add service as a dependency in audits.component.ts

ng generate service audit-service

10. Create service method getAudits(pageIndex,pageSize, filter?) inside the service file and call the backend endpoint to retrieve the audit details based on pageIndex, pageSize and filter will be optional.

**public headers:HttpHeaders= new HttpHeaders({
'Content-Type':'application/json',
'Accept':"application/json",
'Access-Control-Allow-Methods':'GET,POST,PUT,DELETE',
'Authorization':''
});

constructor(private http:HttpClient) { }public getAudits(pageIndex,pageSize, filter?){
let params= new HttpParams();
if(filter){
if(filter.statusCode){
params = params.append('statusCode', filter.statusCode);
}
if(filter.statusMessage){
params = params.append('statusMessage', filter.statusMessage);
}
if(filter.email){
params = params.append('email',filter.email);
}
} return this.http.get(`[localhost:3000/public/audits/${pageIndex}/${pageSize}`,{headers](localhost:3000/public/audits/$%7BpageIndex%..) :this.headers, params})
}**

11. Call this above service method from the audits.component.ts file and to test add console.log.

public getAudits(pageIndex,pageSize){
this.audit.getAudits(pageIndex,pageSize, formValues).subscribe((res: any)=>{
console.log(res);
},
error=>{
console.error(error.message);
})
}

12. After that create the datasource variable, also create the model file under the app/models folder, and export the Audit Entry Interface. Add the audit entry as an import statement in side audits.component.ts and give the data source type as AuditEntry[].

export interface AuditEntry{
clientIp: string;
clientIpDetails: IpDetails[]
createdAt: any;
email: string;
hostname: string;
serverIp: string;
serverIpDetails: IpDetails[];
statusCode: string | number;
statusMessage: any;
updatedAt: any;
uri: any;
_id: string | number;
}

export interface IpDetails{
city: string;
country: string;
ip: string;
loc: any;
org: string;
postal: any;
readme: any;
region: any;
timezone: any;
_id: string | number
}

  • Import AuditService and AuditEntry entry inside audits.component.ts

import { AuditService } from 'src/app/apis/audit.service';
import { AuditEntry } from 'src/app/models/audit.model';

  • Update data source type as AuditEntry[].

public dataSource: AuditEntry[];

13. Store the response in both datasource and total count as below.

public getAudits(pageIndex,pageSize){
this.audit.getAudits(pageIndex,pageSize, formValues).subscribe((res: any)=>{
this.dataSource = res.audits;
this.totalCount = res.totalCount;
},
error=>{
console.error(error.message);
})
}

14. Create variable paginator variable and give type as mat paginator and apply @viewchild on that variable, in that way you were able to access the entire element of mat-paginator.

import { MatPaginator, PageEvent } from '@angular/material/paginator';

15. Oops!!!, we have not added HTML content. Add HTML content for displaying the table as below.

  • set displayedColumns[] to two items e.g. [createdAt, updatedAt]

*




<th mat-header-cell \
matHeaderCellDef> CREATED AT
{{element.createdAt}}

        <ng-container matColumnDef="updatedAt">  
            <th mat-header-cell \*matHeaderCellDef> UPDATED AT  </th>  
            <td mat-cell \*matCellDef="let element"> {{element.updatedAt}} </td>  
        </ng-container>  

        <tr mat-header-row \*matHeaderRowDef="displayedColumns"></tr>  
        <tr mat-row \*matRowDef="let row; columns: displayedColumns;"></tr>  
    </table>  

**

  • After that add all the columns to displayedColumns[] and add HTML related to columns inside the table. Test the UI in the browser for changes.

  • Add a paginator tag below the table to display page options for lazy loading. And create pageNavigate(page:PageEvent) method inside audits.component.ts add call the getUsers(pageIndex,pageSize).

Test the changes by running ng serve and open URI in browser “localhost:4200/audits”. You can able to see the page options and by clicking on the next page, you can able to see new records.

Output Screens :

Screen #1:

Screen #2:

Source Code:

Front End:
GitHub:
mryenagandula/angular-material-table

Back End:
GitHub:
mryenagandula/Letstalk-Backend

Live Backend URI: letstalk-be.herokuapp.com

Stack blitz Project Preview: stackblitz.com/edit/github-angular-material..

Thanks for reading my article, Please share your feedback, claps, and comments. In that way, it will be helped me to improve my articles in the future. Please share my story with your near and dear, Also follow and subscribe to the medium.