Skip to main content

Angular(v14) | Angular Material(v14) | CRUD Example

In this article, we are going to implement a CRUD example sample of Angular(v14) using the Angular Material(v14) UI components.

Angular:

Angular is a framework that can be used to build a single-page application. Angular applications are built with components that make our code simple and clean.
  • Angular components compose of 3 files like TypeScript(*.ts), HTML File(*.html), CSS File(*.css)
  • Components typescript file and HTML file support 2-way binding which means data flow is bi-directional.
  • The component typescript file listens for all HTML events from the HTML file.

Create Angular(14) Application:

Let's create the Angular(14) application to accomplish our demo.

Make sure to install the Angular CLI tool into our local machine because it provides easy CLI commands to play with the angular application.
npm install -g @angular/cli

Run the below command to create Angular application
ng new name_of_your_project

While creating the app CLI needs a few inputs from us:
  • (1) Add the Angular routing
  • (2) Angular support styles sheet files like 'CSS', 'SCSS', 'Sass', 'Less'. For this demo, I choose 'CSS' file type.
Let's explore a few default files in the angular project.
  • package.json - contains commands like build, run, test, etc. It also contains packages or library references that our angular application requires.
  • angular.json - contains setup and configurations of angular.
  • src/index.html - only HTML file of the angular application it contains the root angular component element like 'app-root', the area for the component to render
  • src/main.ts -entry file of our angular application to execute.
  • src/app/app.module.ts - entry module
  • src/app/app-routing.module.ts - entry route module.
  • app(folder or root component folder) - contains root component like 'AppComponent' that consists of files like 'app.component.ts', 'app.component.html', 'app.component.css'.

Install Angular Material Library:

Let's install the Angular Material library into our application
ng add @angular/material
While installing the library CLI expects a few inputs from us:
  • (1)It asks us to choose a theme
  • (2)Ask us to set up angular typography styles, we can say 'yes' to it.
  • (3) It asks us to enable animations or not, we can say 'yes' to it.

Toolbar Angular Material Component To Create Menu:

Let's use the Angular Material Toolbar component for to create a Menu for our sample. So let's replace the HTML content in 'app.component.html'
src/app/app.component.html:
<mat-toolbar color="primary">
  <span>Students</span>
</mat-toolbar>

<router-outlet></router-outlet>
  • (Line: 1-3) Rendered our angular material toolbar component element.
  • (Line: 5) The 'router-outlet' angular component element here routed components or page-level components get rendered.
Import 'MatToolbarModule' in the 'AppModule'.
src/app/app.module.ts:
import { MatToolbarModule } from '@angular/material/toolbar';
// existing code hidden for display purpose
@NgModule({
  imports: [
    MatToolbarModule,
  ]
})
export class AppModule {}

Setup JSON Server:

Let's set up a fake API by setting up the JSON server in our local machine.

Run the below command to install the JSON server globally onto our local system.
npm install -g json-server

Now go to our angular application and add a command to run the JSON server into the 'package.json' file.
"json-run":"json-server --watch db.json"


Now to invoke the above-added command, run the below command in the angular application root folder.
npm run json-run

After running the above command for the first time, a 'db.json' file gets created, so this file act as a database. So let's add some sample data into the file as below.

Now access API endpoint like 'http://localhost:3000/students'.

Create Angular Component 'AllStudents':

Let's create a new angular component like 'AllStudentsComponent'.
ng generate component allStudents --skip-tests


Configure route for 'AllStudentsComponent' component in 'AppRoutingModule'.
src/app/app-routing.module.ts:
import { AllStudentsComponent } from './all-students/all-students.component';
//existing code hidden for display purpose
const routes: Routes = [
  {
    path: '',
    component: AllStudentsComponent,
  },
];
  • Here empty path represents that is the home URL and is mapped to our 'AllStudentComponent'.

Create Angular Service 'Students':

Let's create an angular service like 'StudentsService', where we are going to write our API calls logic.
ng generate service students --skip-tests

Now inject the 'HttpClient' instance into the service constructor. The 'HttpClient' provides in-built methods for invoking the API calls.
src/app/students.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root',
})
export class StudentsService {
  constructor(private httpClient: HttpClient) {}
}
Now import 'HttpClientModule' in the 'AppModule'.
src/app/app.module.ts:
import { HttpClientModule } from '@angular/common/http';
// existing code hidden for display purpose
@NgModule({
  imports: [
    HttpClientModule
  ]
})
export class AppModule {}

Create API Response Model 'Student':

Let's create an API response model like 'Student'.
ng generate interface student
src/app/student.ts:
export interface Student {
  id: number;
  firstName: string;
  lastName: string;
  gender: string;
  age: number;
}

Initial CSS To Sylte.css File:

Let's add a small flex design style in our 'style.css' for to center the content.
src/style.css:
.container {
  display: flex;
  align-items: center;
  justify-content: center;
}

Read Operation:

The read operation means fetching the data from the API and then bind to the UI.

In our 'StudentsService' let's implement our logic to invoke the get API call.
src/app/student.service.ts:
get(): Observable<Student[]> {
 return this.httpClient.get<Student[]>('http://localhost:3000/students');
}
Let's add a few CSS styles to 'all-students.component.html' file
src/app/all-students/all-students.component.html:
table {
  width: 80%;
}

.allstudents-container {
  padding: 20px;
}
Let's add the following logic into the 'app.component.ts'.
src/app/app.component.html:
import { Component, OnInit } from '@angular/core';
import { Student } from '../student';
import { StudentsService } from '../students.service';

@Component({
  selector: 'app-all-students',
  templateUrl: './all-students.component.html',
  styleUrls: ['./all-students.component.css'],
})
export class AllStudentsComponent implements OnInit {
  allStudentsSource: Student[] = [];
  displayedColumns: string[] = ['id', 'firstName',  'gender', 'lastName', 'age'];

  constructor(private studentService: StudentsService) {}

  ngOnInit(): void {
    this.get();
  }

  get() {
    this.studentService.get().subscribe((data) => {
      this.allStudentsSource = data;
    });
  }
}
  • (Line: 5-10) To make our 'AllStudentsComponent' an angular component we have to decorate our class with '@Component' attribute that loads from the '@angular/core'. The 'selector' property defines the component HTML element tag. The 'templateUrl' property links the component HTML file.
  • (Line: 11) The 'allStudentSource' variable to store the API response data.
  • (Line: 12) The 'displayedColumns' variable to register the columns we want to display on the material table. The order of columns of the material table depends on the order in which columns are registered with the 'displayColumns' variable,
  • (Line: 14) Injected our 'StudentService'.
  • (Line: 20-24) Invoking the GET API call and API response stored to the 'allStudentsSource' variable.
  • (Line: 16-18) The 'ngOnInit' is an angular life cycle method that executes on component renders. So in this method, we will invoke our  'get()' method.
Let's add the following logic into the 'app.component.html'.
src/app/app.component.html:
<div class="container allstudents-container">
  <table mat-table [dataSource]="allStudentsSource" 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="firstName">
      <th mat-header-cell *matHeaderCellDef>First Name</th>
      <td mat-cell *matCellDef="let element">{{ element.firstName }}</td>
    </ng-container>

    <ng-container matColumnDef="lastName">
      <th mat-header-cell *matHeaderCellDef>Last Name</th>
      <td mat-cell *matCellDef="let element">{{ element.lastName }}</td>
    </ng-container>

    <ng-container matColumnDef="gender">
      <th mat-header-cell *matHeaderCellDef>Gender</th>
      <td mat-cell *matCellDef="let element">{{ element.gender }}</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>
</div>
  • (Line: 12) The 'dataSource' is material table property that expects array of data that needs to be rendered on the table.
  • The 'matColumnDef' value must be one of the values registered in the 'displayedColumns' variable.
  • The 'matCellDef' attributes can read the each individual item from the 'dataSource' variable.
  • In angular data binding done with '{{}}' (string interpolation)
Let's import the 'MatTableModule' into the 'AppModule'.
src/app/app.module.ts:
import { MatTableModule } from '@angular/material/table';
// existing code hidden for display purpose
@NgModule({
  imports: [
    MatTableModule,
  ]
})
export class AppModule {}

Create Angular Component 'AddStudent':

Let's create a new angular component like 'AddStudent'.
ng generate component add-student --skip-tests


Let's add the route for 'AddStudentComponent' in the 'AppRoutingModule'.
src/app/app-routing.module.ts:
import { AddStudentComponent } from './add-student/add-student.component';
// existing code hidden for display purpose
const routes: Routes = [
  {
    path:'add-student',
    component: AddStudentComponent
  }
];

Create Operation:

Let's implement the logic to invoke the HTTP POST API call to create an item in the 'StudentsService'.
src/app/students.service.ts:
create(payload:Student){
 return this.httpClient.post<Student>('http://localhost:3000/students', payload);
}
  • The 'HttpClient.post<T>()' method invokes the HTTP Post endpoint to create an item.
Let's add the following logic into the 'add-student.component.ts' file.
src/app/add-student/add-student.component.ts:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Student } from '../student';
import { StudentsService } from '../students.service';

@Component({
  selector: 'app-add-student',
  templateUrl: './add-student.component.html',
  styleUrls: ['./add-student.component.css'],
})
export class AddStudentComponent implements OnInit {
  studentForm: Student = {
    id: 0,
    firstName: '',
    lastName: '',
    gender: 'Male',
    age: 0,
  };

  constructor(
    private studentService: StudentsService,
    private router: Router
  ) {}

  ngOnInit(): void {}

  create() {
    this.studentService.create(this.studentForm).subscribe(() => {
      this.router.navigate(['/']);
    });
  }
}
  • (Line: 12-18) The 'studentForm' object will be used for our form model binding.
  • (Line: 21-22) The 'StudentService' and 'Router' services are injected into our constructor.
  • (Line: 27-31) The 'create()' method will be registered for the form submit button click event. Here we invoke our HTTP Post API call. On API call success navigate the page back to the home page.
Let's add a few CSS in 'add-student.component.css'
src/app/add-student/add-student.component.css:
.form-element{
  width: 500px;
}
.add-student-container{
  padding: 20px;
}
Let's add the following HTML content to the 'add-student.component.html'.
src/app/add-student/add-student.component.html:
<div class="container add-student-container">
  <div>
    <mat-card>
      <h3 style="text-align: center">Add New Students Data</h3>
      <div>
        <mat-form-field appearance="outline" class="form-element">
          <mat-label>First Name</mat-label>
          <input matInput  [(ngModel)] ="studentForm.firstName" />
        </mat-form-field>
      </div>

      <div>
        <mat-form-field appearance="outline" class="form-element">
          <mat-label>Last Name</mat-label>
          <input matInput [(ngModel)] ="studentForm.lastName"/>
        </mat-form-field>
      </div>
      <div>
        <mat-form-field appearance="outline" class="form-element">
          <mat-label>Gender</mat-label>
          <mat-select [(ngModel)] ="studentForm.gender">
            <mat-option value="Male">Male</mat-option>
            <mat-option value="Female">Female</mat-option>
          </mat-select>
        </mat-form-field>
      </div>
      <div>
        <mat-form-field appearance="outline" class="form-element">
          <mat-label>Age</mat-label>
          <input matInput  type="number" [(ngModel)] ="studentForm.age"/>
        </mat-form-field>
      </div>
      <div>
        <button mat-raised-button color="primary" (click)="create()">Create</button>
      </div>
    </mat-card>
  </div>
</div>
  • (Line: 3) The 'mat-card' used an angular material card component.
  • The 'mat-form-field' means angular material form  field component. Here we used angular form binding using '[(ngModel)]'.
  • (Line: 34) The material button click event registered with the 'create()' method.
Since we had used a lot of angular material components so we have to import related material modules on the 'AppModule'.
src/app/app.module.ts:
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatCardModule } from '@angular/material/card';
import { MatSelectModule } from '@angular/material/select';
import {MatButtonModule} from '@angular/material/button';
import { FormsModule } from '@angular/forms';
// existing code hidden for display purpose
@NgModule({
  
  imports: [
    MatFormFieldModule,
    MatInputModule,
    MatCardModule,
    MatSelectModule,
    MatButtonModule,
    FormsModule
  ]
})
export class AppModule {}
  • Here we can observe imported all required material modules. The 'ForModule' is an angular module imported because we are using '[(ngModel)]' for form binding.
Navigate from the 'AllStudentsComponent' to  'AddStudentsComponent' lets add anchor link  button in 'AllStudentsComponent'
src/app/all-students.component.ts:
<div class="container allstudents-container">
  <a mat-raised-button color="primary" routerLink="/add-student">Add</a>
</div>
(Step 1)

(Step 2)

(Step 3)

Create Angular Component 'EditStudent':

Let's create a new angular component like 'EditStudent'.
ng generate component edit-student --skip-tests


Let's configure the 'EditStudentComponent' route in the 'AppRoutingModule'.
src/app/app-routing.module.ts:
import { EditStudentComponent } from './edit-student/edit-student.component';
// existing code hidden for display purpose
const routes: Routes = [
  {
    path: 'edit-student/:id',
    component: EditStudentComponent,
  },
];
  • Here path contains a dynamic placeholder ':id' which can be our item 'id' value in the URL.

Update Operation:

Let's implement the logic to invoke the HTTP PUT API call to update the item in our 'StudentsService'.
src/app/students.service.ts:
getById(id: number): Observable<Student> {
  return this.httpClient.get<Student>(`http://localhost:3000/students/${id}`);
}

update(payload: Student): Observable<Student> {
 return this.httpClient.put<Student>(
  `http://localhost:3000/students/${payload.id}`,
  payload
 );
}
  • (Line: 1-3) Here invoking the HTTP GET Endpoint by 'id' value which is the item to be edited.
  • (Line: 5-10) The 'HttpClient.put()' method invokes updating the item.
let's add some CSS styles to 'edit-student.component.css' file.
src/app/edit-student/edit-student.component.css:
.form-element {
  width: 500px;
}
.add-student-container {
  padding: 20px;
}
Let's add the following logic to 'edit-student.component.ts' file
src/app/edit-student/edit-student.component.ts:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Student } from '../student';
import { StudentsService } from '../students.service';

@Component({
  selector: 'app-edit-student',
  templateUrl: './edit-student.component.html',
  styleUrls: ['./edit-student.component.css'],
})
export class EditStudentComponent implements OnInit {
  studentForm: Student = {
    id: 0,
    firstName: '',
    lastName: '',
    gender: 'Male',
    age: 0,
  };

  constructor(
    private studentService: StudentsService,
    private router: Router,
    private route: ActivatedRoute
  ) {}

  ngOnInit(): void {
    this.route.paramMap.subscribe((param) => {
      var id = Number(param.get('id'));
      this.getById(id);
    });
  }

  getById(id: number) {
    this.studentService.getById(id).subscribe((data) => {
      this.studentForm = data;
    });
  }

  update() {
    this.studentService.update(this.studentForm).subscribe(() => {
      this.router.navigate(['/']);
    });
  }
}
  • (Line: 23) Injected the 'ActivatedRoute' that loads from the '@angular/router'
  • (Line: 27-30) Reading the 'id' value from the URL.
  • (Line: 33) The HTTP GET endpoint by 'id' value for to update the item.
  • (Line: 39-43) Invoking the Update API call.
Let's add the following HTML content into the 'edit-student.component.html'.
src/app/edit-student/edit-student.component.html:
<div class="container add-student-container">
    <div>
      <mat-card>
        <h3 style="text-align: center">Update Students Data</h3>
        <div>
          <mat-form-field appearance="outline" class="form-element">
            <mat-label>First Name</mat-label>
            <input matInput  [(ngModel)] ="studentForm.firstName" />
          </mat-form-field>
        </div>
  
        <div>
          <mat-form-field appearance="outline" class="form-element">
            <mat-label>Last Name</mat-label>
            <input matInput [(ngModel)] ="studentForm.lastName"/>
          </mat-form-field>
        </div>
        <div>
          <mat-form-field appearance="outline" class="form-element">
            <mat-label>Gender</mat-label>
            <mat-select [(ngModel)] ="studentForm.gender">
              <mat-option value="Male">Male</mat-option>
              <mat-option value="Female">Female</mat-option>
            </mat-select>
          </mat-form-field>
        </div>
        <div>
          <mat-form-field appearance="outline" class="form-element">
            <mat-label>Age</mat-label>
            <input matInput  type="number" [(ngModel)] ="studentForm.age"/>
          </mat-form-field>
        </div>
        <div>
          <button mat-raised-button color="primary" (click)="update()">Update</button>
        </div>
      </mat-card>
    </div>
  </div>
Let's configure the edit button in 'AllStudentComponent'.
src/app/all-students/all-students.component.ts:
displayedColumns: string[] = ['id', 'firstName',  'gender', 'lastName', 'age','actions'];
  • Here 'actions' is the additional column name configured.
src/app/all-students/all-students.component.html:
<ng-container matColumnDef="actions">
  <th mat-header-cell *matHeaderCellDef>Actions</th>
  <td mat-cell *matCellDef="let element">
	<a [routerLink]="['/edit-student', element.id]"
	  ><mat-icon
		aria-hidden="false"
		aria-label="Example home icon"
		fontIcon="edit"
	  >
	  </mat-icon
	></a>
  </td>
</ng-container>
  • Here is our new 'actions' column. Here we can observe an anchor tag with an edit page route and here we use a material edit icon.
Now in 'AppModule' import the 'MatIconModule'.
src/app.module.ts:
import {MatIconModule} from '@angular/material/icon';
// existing code hidden for display purpose
@NgModule({
  imports: [
    MatIconModule
  ]
})
export class AppModule {}
(Step 1)
(Step 2)
(Step 3)

Delete Operation:

Let's implement the logic to invoke the HTTP DELETE endpoint for deleting an item in the 'StudentService'.
src/app/students.service.ts:
delete(id: number) {
 return this.httpClient.delete(`http://localhost:3000/students/${id}`);
}
  • Here 'HttpClient.delete()' method invokes the HTTP Delete endpoint.
Now to display the delete confirmation dialog we are going to use the angular material dialog box. So let's create a new component like 'DeleteDialogStudent'.
ng generate component delete-dialog-student --skip-tests


Let's add the following logic into the 'delete-dialog-student.component.ts'
src/app/delete-dialog-student/delete-dialog-student.component.ts:
import { Component, Inject, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { StudentsService } from '../students.service';

@Component({
  selector: 'app-delete-dialog-student',
  templateUrl: './delete-dialog-student.component.html',
  styleUrls: ['./delete-dialog-student.component.css'],
})
export class DeleteDialogStudentComponent implements OnInit {
  constructor(
    public dialogRef: MatDialogRef<DeleteDialogStudentComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private studentService: StudentsService
  ) {}

  ngOnInit(): void {}

  confirmDelete() {
   this.studentService.delete(this.data.id).subscribe(() => {
      this.dialogRef.close(this.data.id);
    });
  }
}
  • (Line: 12) The  'MatDialogRef' loads from the '@angular/material/dialog. The 'MatDialogRef' control over the dialog box inside of it.
  • (Line: 13) The 'MAT_DIALOG_DATA' token reads the data from the parent component that invokes our dialog.
  • (Line: 14) Injected our 'StudentService'.
  • (Line: 19-23) The 'confirmDelete' method invokes the HTTP Delete API call. After API call completes we will close the dialog by using the 'dialog.close()' method.
Let's add the following HTML in 'delete-dialog-student.component.html'.
src/app/delete-dialog-student/delete-dialog-student.component.html:
<h1 mat-dialog-title>Delete Item</h1>
<div mat-dialog-content>
  Would you like to delete ?
</div>
<div mat-dialog-actions>
  <button mat-button mat-dialog-close>No</button>
  <button mat-button (click)="confirmDelete()" cdkFocusInitial>Ok</button>
</div>
  • (Line: 7) Here registered with the 'confirmDelete' method.
Now add the material dialog material module into the 'MatDialogModule'.
src/app-routing.module.ts:
import {MatDialogModule} from '@angular/material/dialog';

@NgModule({
  imports: [
    MatDialogModule
  ]
})
export class AppModule {}
Let's add the following logic into the 'all-students.component.ts' file.
src/app/all-students/all-students.component.ts:
import { Component, OnInit } from '@angular/core';
import { Student } from '../student';
import { StudentsService } from '../students.service';
import { MatDialog } from '@angular/material/dialog';
import { DeleteDialogStudentComponent } from '../delete-dialog-student/delete-dialog-student.component';

@Component({
  selector: 'app-all-students',
  templateUrl: './all-students.component.html',
  styleUrls: ['./all-students.component.css'],
})
export class AllStudentsComponent implements OnInit {
  allStudentsSource: Student[] = [];
  displayedColumns: string[] = [
    'id',
    'firstName',
    'gender',
    'lastName',
    'age',
    'actions',
  ];

  constructor(
    private studentService: StudentsService,
    public dialog: MatDialog
  ) {}

  ngOnInit(): void {
    this.get();
  }

  get() {
    this.studentService.get().subscribe((data) => {
      this.allStudentsSource = data;
    });
  }

  openDeleteModal(id: number) {
    const dialogRef = this.dialog.open(DeleteDialogStudentComponent, {
      width: '250px',
      data: { id },
    });

    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
        this.allStudentsSource = this.allStudentsSource.filter(
          (_) => _.id !== id
        );
      }
    });
  }
}
  • (Line: 25) Inject the 'MatDailog' that loads from the '@angular/material/dialog.
  • (Line: 39-42) Open the material dialog box and also we pass the item 'id' value that needs to be deleted.
  • (Line: 44-51) The 'afterClosed()' method executes after closing the material dialog. Here it receives the item 'id' value when we click on the 'Ok' button on the dialog,
src/app/all-students/all-students.component.html:
<ng-container matColumnDef="actions">
  <th mat-header-cell *matHeaderCellDef>Actions</th>
  <td mat-cell *matCellDef="let element">
	<a [routerLink]="['/edit-student', element.id]"
	  ><mat-icon
		aria-hidden="false"
		aria-label="Example home icon"
		fontIcon="edit"
	  >
	  </mat-icon
	></a>
	<mat-icon
	  (click)="openDeleteModal(element.id)"
	  aria-hidden="false"
	  aria-label="Example delete icon"
	  fontIcon="delete"
	>
	</mat-icon>
  </td>
</ng-container>
  • (Line: 12-18) Rendered the material delete icon whose click event registered with 'openDeleteModal()' method.

Support Me!
Buy Me A Coffee PayPal Me

Video Session:

Wrapping Up:

Hopefully, I think this article delivered some useful information on Angular 14 CRUD using the Angular Material UI library. using I love to have your feedback, suggestions, and better techniques in the comment section below.

Refer:

Follow Me:

Comments

  1. without refresh how can we delete the particular row

    ReplyDelete

Post a Comment

Popular posts from this blog

Angular 14 Reactive Forms Example

In this article, we will explore the Angular(14) reactive forms with an example. Reactive Forms: Angular reactive forms support model-driven techniques to handle the form's input values. The reactive forms state is immutable, any form filed change creates a new state for the form. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously. Some key notations that involve in reactive forms are like: FormControl - each input element in the form is 'FormControl'. The 'FormControl' tracks the value and validation status of form fields. FormGroup - Track the value and validate the state of the group of 'FormControl'. FormBuilder - Angular service which can be used to create the 'FormGroup' or FormControl instance quickly. Form Array - That can hold infinite form control, this helps to create dynamic forms. Create An Angular(14) Application: Let'

.NET 7 Web API CRUD Using Entity Framework Core

In this article, we are going to implement a sample .NET 7 Web API CRUD using the Entity Framework Core. Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, and desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains programming functions that can be requested via HTTP calls either to fetch or update data for their respective clients. Some of the Key Characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build the REST full services. Install The SQL Server And SQL Management Studio: Let's install the SQL server on our l

ReactJS(v18) JWT Authentication Using HTTP Only Cookie

In this article, we will implement the ReactJS application authentication using the HTTP-only cookie. HTTP Only Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing the JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-ONly cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use the authentication with HTTP-only JWT cookie then we no need to implement the custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To authenticate our client application with JWT HTTP-only cookie, I developed a NetJS(which is a node) Mock API. Check the GitHub link and read the document on G

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

Angular 14 State Management CRUD Example With NgRx(14)

In this article, we are going to implement the Angular(14) state management CRUD example with NgRx(14) NgRx Store For State Management: In an angular application to share consistent data between multiple components, we use NgRx state management. Using NgRx state helps to avoid unwanted API calls, easy to maintain consistent data, etc. The main building blocks for the NgRx store are: Actions - NgRx actions represents event to trigger the reducers to save the data into the stores. Reducer - Reducer's pure function, which is used to create a new state on data change. Store - The store is the model or entity that holds the data. Selector - Selector to fetch the slices of data from the store to angular components. Effects - Effects deals with external network calls like API. The effect gets executed based the action performed Ngrx State Management flow: The angular component needs data for binding.  So angular component calls an action that is responsible for invoking the API call.  Aft

Angular 14 Crud Example

In this article, we will implement CRUD operation in the Angular 14 application. Angular: Angular is a framework that can be used to build a single-page application. Angular applications are built with components that make our code simple and clean. Angular components compose of 3 files like TypeScript File(*.ts), Html File(*.html), CSS File(*.cs) Components typescript file and HTML file support 2-way binding which means data flow is bi-directional Component typescript file listens for all HTML events from the HTML file. Create Angular(14) Application: Let's create an Angular(14) application to begin our sample. Make sure to install the Angular CLI tool into our local machine because it provides easy CLI commands to play with the angular application. Command To Install Angular CLI npm install -g @angular/cli Run the below command to create the angular application. Command To Create Angular Application ng new name_of_your_app Note: While creating the app, you will see a noti

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

ReactJS(v18) Authentication With JWT AccessToken And Refresh Token

In this article, we are going to do ReactJS(v18) application authentication using the JWT Access Token and Refresh Token. JSON Web Token(JWT): JSON Web Token is a digitally signed and secured token for user validation. The JWT is constructed with 3 important parts: Header Payload Signature Create ReactJS Application: Let's create a ReactJS application to accomplish our demo. npx create-react-app name-of-your-app Configure React Bootstrap Library: Let's install the React Bootstrap library npm install react-bootstrap bootstrap Now add the bootstrap CSS reference in 'index.js'. src/index.js: import 'bootstrap/dist/css/bootstrap.min.css' Create A React Component 'Layout': Let's add a React component like 'Layout' in 'components/shared' folders(new folders). src/components/shared/Layout.js: import Navbar from "react-bootstrap/Navbar"; import { Container } from "react-bootstrap"; import Nav from "react-boot

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually