Skip to main content

Angular(v14) | GraphQL Client - Apollo Angular(v3) | JSON Server GraphQL Fake Endpoint | CRUD Example

In this article, we will implement Angular(v14) CRUD to consume the GraphQL endpoint using the Apollo Angular(v3) library.

GraphQL API:

  • GraphQL API mostly has a single endpoint. So data fetching or updating will be carried out by that single endpoint. For posting data or querying data, we have to follow its own syntax. GraphQL carries two essential operations:
  • Query - (Fetching Data)
  • Mutation - (Saving Data)

Create An Angular(v14) Application:

Let's create an Angular(v14) application to accomplish our demo. 
Command To Create Angular Application
ng new your_app_name

Let's install the bootstrap into our application.
npm install bootstrap

Now configure the CSS and JS links of bootstrap in 'angular.json'.

Let's add the bootstrap 'Navbar' component at 'app.component.html'.
src/app/app.component.html:
<nav class="navbar navbar-dark bg-primary">
  <div class="container-fluid">
    <div class="navbar-brand">
      Fruit Basket
    </div>
  </div>
</nav>

Setup JSON Server For Fake GraphQL Endpoint:

Let's use JSON Server to set up a fake GraphQL endpoint into our local machine.

Now install the JSON GraphQL server globally.
npm install -g json-graphql-server

Create a db.js file within our angular application root folder. Define the API response type with sample data in  'db.js' as below.
src/db.js:
module.exports = {
    fruits:[
        {
            id:1,
            name: "mango",
            quantity:2,
            price:500
        }
    ]
}
Now let's add a command in 'package.json' to run the GraphQL server.

Now start the GraphQL server, and run the below command in the terminal.
npm run graphql-run

Then if we access the "http://localhost:3000" it opens up the GraphQL UI tool interact with the graphQL server.

Install Apollo Angular(GraphQL Client) Package:

Install the Apollo Angular package.
ng add apollo-angular

After the package is installed, it generates a file like the 'graphql.module.ts', in this file, we have to configure our GraphQL Url
src/app/graphql.module.ts:

Create A Feature Module(Fruit Module) And A Child Component(Home Component):

Let's create a Feature Module/Child Module like the 'Fruit' Module.
ng generate module fruits --routing

Now configure module-level routing at the 'AppRoutingModule'.
src/app/app-routing.module.ts:
// existing code hidden for display purpose
const routes: Routes = [{
  path:'',
  loadChildren:() => import('./fruits/fruits.module').then(_ => _.FruitsModule)
}];
  • Here configured 'FruitModule' as a lazy loading module.
Now let's create 'Home' component at 'Fruits' Module.
ng generate component fruits/home --skip-tests

Add the 'Home' component route in 'FruitsRoutingModue'.
src/app/fruits/fruits-routing.module.ts:
// existing code hidden for display purpose
import { HomeComponent } from './home/home.component';

const routes: Routes = [{
  path:'',
  component: HomeComponent
}];

Implement Read Operation:

Let's implement the 'Read' operation, fetching data from the GraphQL endpoint and then display on UI.

Let's create a response model for our GraphQL endpoint.
ng generate interface fruits/fruits
src/app/fruits/fruits.ts:
export interface Fruits {
  id: number;
  price: number;
  name: string;
  quantity: number;
}
Now try to frame the GraphQL 'Query' operation to fetch the data.
  • Here 'query' keyword classify our request as fetch operation.
  • Here 'allFruits' keyword is resolver method name at server which serves all the response. So we no need to bother about this name because it will be auto populated in the above tool or we can cross check schema that appears in the above tool.
  • Here we are requesting the server to return 'id', 'price', 'name', and 'quantity' properties only as the part of the response.
  • In the response we can observe root object 'data', then we will have property which name matches with our request resolver method(eg: allFruits).
Let's create file to store the 'Query' like 'fruits-query.ts'
ng generate class fruits/gql/fruits-query --skip-tests
src/app/fruits/gql/fruits-query.ts:
import { gql } from "apollo-angular";

export const GET_Fruits = gql`
query{
  allFruits{
    id,
    price,
    name,
    quantity
  }
}
`
  • Here we have enclose our 'Query' inside of the 'gql' that loads from the 'apollo-angular'.
Let's add the following logic in 'home.component.ts'.
src/app/fruits/home/home.component.ts:
import { Component, OnInit } from '@angular/core';
import { Apollo } from 'apollo-angular';
import { map, Observable, of } from 'rxjs';
import { Fruits } from '../fruits';
import { GET_Fruits } from '../gql/fruits-query';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
  constructor(private apollo: Apollo) {}

  allFruits$: Observable<Fruits[]> = of([]);

  ngOnInit(): void {
    this.allFruits$ = this.apollo
      .watchQuery<{ allFruits: Fruits[] }>({ query: GET_Fruits })
      .valueChanges.pipe(map((result) => result.data.allFruits));
  }
}
  • (Line: 13) Injected the 'Apollo' instance that loads from the 'apollo-angular'.
  • (Line: 15) Declare and initialized the 'allFruits$' variable of type 'Observable<Fruits[]>'.
  • (Line: 18-20) Here 'watchQuery<{ allFruits: Fruits[] }>()' used for GraphQL 'Query' operation. It takes our 'GET_Fruits' as input parameter. Finally assigning the API response to the 'allFruits$' variable.
src/app/fruits/home/home.component.html:
<div class="container">
  <table class="table">
    <thead>
      <tr>
        <th scope="col">Id</th>
        <th scope="col">Name</th>
        <th scope="col">Quantity</th>
        <th scope="col">Price</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let item of allFruits$ | async">
        <th scope="row">{{ item.id }}</th>
        <td>{{ item.name }}</td>
        <td>{{ item.quantity }}</td>
        <td>{{ item.price }}</td>
        
      </tr>
    </tbody>
  </table>
</div>

Create 'Add' Component:

Let's create a new component like 'Add' under the 'Fruits' module.
ng generate component fruits/add --skip-tests

Let's configure the 'Add' component route in 'FruitRouteModule'.
src/app/fruits/fruits-routing.module.ts:
import { AddComponent } from './add/add.component';
// existing code for display purpose
const routes: Routes = [
  {
    path: 'add',
    component: AddComponent
  },
]

Implement Create Operation:

Let's implement 'Create' operation like posting data to the GraphQL endpoint.

Let's try to frame the GraphQL 'Mutation' operation to save the data.

  • Here 'mutation' keyword represent posting the data.Here 'String!'(Non-nullable string), 'Int!'(Non-nullable initiger types) are GraphQL type. Here '$name', '$quantity', '$price' variable names at the bottom where we pass our data to them.
  • Here 'createFruit' is an resolver method, I framed this 'Mutation' based on the schema provided by the tool above.
Let's create a file for GraphQL 'mutations' like 'fruits-mutation.ts'
ng generate class fruits/gql/fruits-mutation --skip-tests
src/app/fruits/gql/fruits-mutation.ts:
import { gql } from "apollo-angular";


export const CREATE_Fruit = gql`
mutation($name:String!, $quantity:Int!, $price: Int!){
  createFruit(name:$name, quantity: $quantity, price: $price){
    id,
    name,
    quantity,
    price
  }
}
`
  • Here our mutation wrapped around the 'gql' that loads from the 'apollo-angular'.
Let's add the following logic into 'add.component.html'.
src/app/fruits/add/add.component.html:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Apollo } from 'apollo-angular';
import { Fruits } from '../fruits';
import { CREATE_Fruit } from '../gql/fruits-mutation';
import { GET_Fruits } from '../gql/fruits-query';

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.css'],
})
export class AddComponent implements OnInit {
  constructor(private apollo: Apollo, private router: Router) {}

  fruitForm: Fruits = {
    id: 0,
    name: '',
    price: 0,
    quantity: 0,
  };

  ngOnInit(): void {}

  create() {
    this.apollo
      .mutate<{ createFruit: Fruits }>({
        mutation: CREATE_Fruit,
        variables: {
          name: this.fruitForm.name,
          price: this.fruitForm.price,
          quantity: this.fruitForm.quantity,
        },
        update: (store, { data }) => {
          if (data?.createFruit) {
            var allData = store.readQuery<{ allFruits: Fruits[] }>({
              query: GET_Fruits,
            });

            if (allData && allData?.allFruits?.length > 0) {
              var newData: Fruits[] = [...allData.allFruits];
              newData?.unshift(data.createFruit);

              store.writeQuery<{ allFruits: Fruits[] }>({
                query: GET_Fruits,
                data: { allFruits: newData },
              });
            }
          }
        },
      })
      .subscribe(({ data }) => {
        this.router.navigate(['/']);
      });
  }
}
  • (Line: 14) Injected 'Apollo' instance that loads from the 'apollo-angular'. Injected 'Router' instance that loads from the '@angular/router'.
  • (Line: 16-21) Declare and initialize the 'fruitForm' variable for form binding.
  • (Line: 26-54) GraphQL mutation invocation.
  • (Line: 27) The 'Apollo.mutate()' method invokes the GraphQL endpoint for saving new record.
  • (Line: 28) Our 'mutation:Create_Fruit' mutation operation.
  • (Line: 29-33) To pass payload to GraphQL endpoint we have to use the 'variables'. Here we mapped our 'fruitFrom' data to the 'variables'.
  • (Line: 34:50) The 'update' property registered with arrow function for updating the angular-apollo cache. By default angular-apollo save the data in 'in-memroy' cache, so newly created record need to updated to cache so that record will be displayed on the table content of 'Home' component.The arrow function contains 2 input parameter like 'store' and '{data}'(mutation response object).
  • (Line: 36-38) The 'store.readQuery' to fetch the data from the in-memory cache store. Here we use 'GET_Fruits' as 'query'.
  • (Line: 41-42)  Pusssing all data from cache into variable 'newData'. Atlast pushing our newly created record into the 'newData'.
  • (Line: 44-47) The 'store.writeQuery' save our 'newData' into the in-memory  cache store.
src/app/fruits/add/add.component.html:
<div class="container">
  <legend>Create Item</legend>
  <form>
    <div class="mb-3">
      <label for="txtName" class="form-label">Name</label>
      <input
        type="text"
        name="name"
        [(ngModel)]="fruitForm.name"
        class="form-control"
        id="txtName"
      />
    </div>
    <div class="mb-3">
      <label for="txtPrice" class="form-label">Price</label>
      <input
        type="number"
        name="price"
        [(ngModel)]="fruitForm.price"
        class="form-control"
        id="txtPrice"
      />
    </div>
    <div class="mb-3">
      <label for="txtQuantity" class="form-label">Quantity</label>
      <input
        type="number"
        name="quantity"
        [(ngModel)]="fruitForm.quantity"
        class="form-control"
        id="txtQuantity"
      />
    </div>
    <button type="button" (click)="create()" class="btn btn-primary">
      Create
    </button>
  </form>
</div>
  • Here added simple form for creating the new item.
Now in 'FruitsModule' import the 'FormsModule'.
src/app/fruits/fruits.module.ts:
import { FormsModule } from '@angular/forms';
// existing code hidden for display purpose
@NgModule({
  imports: [FormsModule],
})
export class FruitsModule {}
(step1)
(step2)

Implement Read Operation With Filters:

Let's implement the 'Read' operation with filters to fetch the data from the GraphQL endpoint.

Now try to frame the GraphQL query operation with filter parameters.
  • Here you can see 'FruitFilter' is a custom type that was at GraphQL serve. It contains different filtering parameters like 'id', 'name', 'name_eq', 'quantity_le', etc can be identify at schema in above tool
  • Here '$fruitFilter' is our variable name.
Let's add our 'query' operation with filters in our 'fruits-query.ts'.
src/app/fruits/gql/fruits-query.ts:
export const GET_Search = gql`
query($fruitFilter:FruitFilter){
  allFruits(filter:$fruitFilter){
    id
    name
    price
    quantity
  }
}
`
Let's add a search by name functionality in the 'Home' component. Add the following HTML in 'home.component.html'.
src/app/fruits/home/home.component.html:
<div class="container">
  <div class="row mt-2">
    <div class="col col-md-4">
      <a class="btn btn-primary" routerLink="/add">Create</a>
    </div>
    <div class="col col-md-6 offset-md-2">
      <div class="input-group mb-3">
        <input type="text" class="form-control"[(ngModel)]="searchName" placeholder="Search By Name" aria-label="Recipient's username" aria-describedby="button-addon2">
        <button class="btn btn-outline-primary" (click)="search()"type="button" id="btnsearch">Search</button>
      </div>
    </div>
  </div>
  <table class="table">
    <!-- exising code hideen for display purpose -->
  </table>
</div>
  • (Line: 8) The 'Input' filed for search. Enabled model binding with 'searchName' property.
  • (Line: 9) Add the 'search' button whose click event registered with the 'search()' method.
Let's implement the 'search()' method in the 'app.component.ts' file.
src/app/fruits/home/home.component.ts:
// existing code hidden for display purpose
export class HomeComponent implements OnInit {
  searchName:string = '';
  
  search() {
    this.allFruits$ = this.apollo.watchQuery<{ allFruits: Fruits[] }>({
      query: GET_Search,
      variables: { fruitFilter: {name:this.searchName} },
    })
    .valueChanges.pipe(map((result) => result.data.allFruits));
  }
}
  • (Line: 3) Declared and initialized the 'searchName' property which is used for model binding with the search box text field.
  • (Line: 8) The 'searchName' is passed as a value to the 'variables'.

Create 'Edit' Component:

Let's create a new angular component like 'Edit' under the 'Fruits' Module.
ng generate component fruits/edit --skip-tests

Now configure the 'Edit' component route in 'Fruits' module.
src/app/fruits/fruits-routing.module.ts:
import { EditComponent } from './edit/edit.component';
// existing code hidden for display purpose
const routes: Routes = [
  {
    path: 'edit/:id',
    component: EditComponent,
  },
];
  • Here edit component route contains a dynamic value that is our 'id' of the item we want to edit.

Implement Update Operation:

Let's implement the 'Update' operation like posting the item to be updated to the GraphQL endpoint.

Now frame the 'mutation' operation for the update.
  • Here 'updateFruit' is the server resolver name we can identify it from the schema in the above tool.
  • Here 'ID!'(Non-nullable JSON ID type), 'String!'(non-nullable string type), 'Int!'(non-nullable intiger type) are GraphQL types
  • Here '$id', '$name', '$quantity', '$price' are GraphQL variables for posting the data.
Let's add the 'mutation' operation for the update operation in the 'fruits-mutation.ts'.
src/app/fruits/gql/fruits-mutation.ts:
export const Update_Fruit = gql`
mutation($id:ID!,$name:String!, $quantity:Int!, $price: Int!){
  updateFruit(id:$id,name:$name, quantity: $quantity, price: $price){
    id,
    name,
    quantity,
    price
  }
}
`
Let's update the logic in 'edit.component.ts' as follows.
src/app/fruits/edit/edit.component.ts:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Apollo } from 'apollo-angular';
import { Fruits } from '../fruits';
import { Update_Fruit } from '../gql/fruits-mutation';
import { GET_Fruits, GET_Search } from '../gql/fruits-query';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css'],
})
export class EditComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private apollo: Apollo,
    private router: Router
  ) {}

  fruitForm: Fruits = {
    id: 0,
    name: '',
    price: 0,
    quantity: 0,
  };

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

  getById(id: number) {
    this.apollo
      .watchQuery>{ allFruits: Fruits[] }<({
        query: GET_Search,
        variables: { fruitFilter: { id } },
      })
      .valueChanges.subscribe(({ data }) =< {
        var fruritById = data.allFruits[0];
        this.fruitForm = {
          id: fruritById.id,
          name: fruritById.name,
          price: fruritById.price,
          quantity: fruritById.quantity,
        };
      });
  }

  update() {
    this.apollo
      .mutate>{ updateFruit: Fruits }<({
        mutation: Update_Fruit,
        variables: {
          name: this.fruitForm.name,
          price: this.fruitForm.price,
          quantity: this.fruitForm.quantity,
          id: this.fruitForm.id,
        },
        update: (store, { data }) =< {
          if (data?.updateFruit) {
            var allData = store.readQuery>{ allFruits: Fruits[] }<({
              query: GET_Fruits,
            });

            if (allData && allData?.allFruits?.length < 0) {
              var newData: Fruits[] = [...allData.allFruits];
              newData = newData.filter((_) =< _.id !== data.updateFruit.id);
              newData.unshift(data.updateFruit);

              store.writeQuery>{ allFruits: Fruits[] }<({
                query: GET_Fruits,
                data: { allFruits: newData },
              });
            }
          }
        },
      })
      .subscribe(({ data }) =< {
        this.router.navigate(['/']);
      });
  }
}
  • (Line: 15) Injected the 'ActivatedRoute' that loads from the '@angular/router'.
  • (Line: 16) Injected the 'Apollo' that loads from the 'apollo-angular'
  • (Line: 17) Injected the 'Router' that loads from the '@angular/router'.
  • (Line: 20-25) The 'fruitForm' declare and initialized which we will use for form model binding.
  • (Line: 28-31) Reading the item 'id' from the URL.
  • (Line: 34-49) The 'getById()' method invokes GraphQL endpoint to fetch the item by 'id'. On successful response, we assign the data to our edit form.
  • (Line: 37-38) Here we use the 'Get_Serch' query operator and in the variable, we pass the 'id' value.
  • (Line: 51-83) The 'update()' method to invoke GraphQL endpoint to updating the records.
  • (Line: 54) The 'Update_Fruit' is our mutation operation
  • (Line: 55-60) Assigning our form data to the GraphQL variables.
  • (Line: 61-78) Just like we updated the apollo-graphql in-memory cache in create operation here also we are updating the record in the in-memory cache.
src/app/fruits/edit/edit.component.html:
<div class="container">
    <legend>Edit Item</legend>
    <form>
      <div class="mb-3">
        <label for="txtName" class="form-label">Name</label>
        <input
          type="text"
          name="name"
          [(ngModel)]="fruitForm.name"
          class="form-control"
          id="txtName"
        />
      </div>
      <div class="mb-3">
        <label for="txtPrice" class="form-label">Price</label>
        <input
          type="number"
          name="price"
          [(ngModel)]="fruitForm.price"
          class="form-control"
          id="txtPrice"
        />
      </div>
      <div class="mb-3">
        <label for="txtQuantity" class="form-label">Quantity</label>
        <input
          type="number"
          name="quantity"
          [(ngModel)]="fruitForm.quantity"
          class="form-control"
          id="txtQuantity"
        />
      </div>
      <button type="button" (click)="update()" class="btn btn-primary">
        update
      </button>
    </form>
  </div>
  • Here form binding is carried with the 'fruitForm' variable and the 'Update' button click event registered with the 'update()' method.
Let's add the 'Edit' button in 'home.component.html'
src/app/fruits/home/home.component.html:
<td>
  <a class="btn btn-primary" [routerLink]="['edit', item.id]"
	>Edit</a>
</td>
(step 1)
(step 2)
(step 3)

Implement Delete Operation:

Let's implement the 'Delete' operation by invoking the GraphQL endpoint for removing the item.

Now frame the mutation operation for removing the item.
  • Here 'removeFruit' is a GraphQL server resolver method we can identify at the above tool
  • Here we use '$id' variable to pass the item 'id' to delete the item at the server
Now let's add our delete mutation command in 'fruits-mutation'.
src/app/fruits/gql/fruits-mutation:
export const Delete_Fruit = gql`
mutation($id:ID!){
  removeFruit(id:$id){
    id
  }
}
`
Let's update the logic in the 'home.component.ts' as follows.
src/app/fruits/home/home.component.ts:
import { Component, OnInit } from '@angular/core';
import { Apollo } from 'apollo-angular';
import { map, Observable, of } from 'rxjs';
import { Fruits } from '../fruits';
import { Delete_Fruit } from '../gql/fruits-mutation';
import { GET_Fruits, GET_Search } from '../gql/fruits-query';

declare var window: any;

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
  constructor(private apollo: Apollo) {}

  allFruits$: Observable<Fruits[]> = of([]);
  searchName: string = '';

  deleteModal: any;
  idTodelete: number = 0;

  ngOnInit(): void {
    this.deleteModal = new window.bootstrap.Modal(
      document.getElementById('deleteModal')
    );

    this.allFruits$ = this.apollo
      .watchQuery<{ allFruits: Fruits[] }>({ query: GET_Fruits })
      .valueChanges.pipe(map((result) => result.data.allFruits));
  }

  search() {
    this.allFruits$ = this.apollo
      .watchQuery<{ allFruits: Fruits[] }>({
        query: GET_Search,
        variables: { fruitFilter: { name: this.searchName } },
      })
      .valueChanges.pipe(map((result) => result.data.allFruits));
  }

  openDeleteModal(id: number) {
    this.idTodelete = id;
    this.deleteModal.show();
  }

  delete() {
    this.apollo
      .mutate<{ removeFruit: Fruits }>({
        mutation: Delete_Fruit,
        variables: {
          id: this.idTodelete,
        },
        update: (store, { data }) => {
          if (data?.removeFruit) {
            var allData = store.readQuery<{ allFruits: Fruits[] }>({
              query: GET_Fruits,
            });

            if (allData && allData?.allFruits?.length > 0) {
              var newData: Fruits[] = [...allData.allFruits];
              newData = newData.filter((_) => _.id == data.removeFruit.id);

              store.writeQuery<{ allFruits: Fruits[] }>({
                query: GET_Fruits,
                data: { allFruits: newData },
              });
            }
          }
        },
      })
      .subscribe(({ data }) => {
        this.deleteModal.hide();
      });
  }
}
  • (Line: 21) Here declare 'deleteModal' variable.
  • (Line: 22) Here declare 'idToDelete' variable.
  • (Line: 25-27) Here assign the bootstrap instance to the 'deleteModal' variable.
  • (Line: 43-46) Here 'openDeleteModal' method shows the delete confirmation modal.
  • (Line: 49-76) Here 'delete()' invokes the GraphQL endpoint for deleting the item.
  • (Line: 51) Here 'Delete_Fruit' our mutation operator.
  • (Line: 53) Passing our 'idToDelete' value to the GraphQL variable
  • (Line: 55-71) Using the 'update' method remove the item from the local in-memory cache.
  • (Line: 74) Close the bootstrap modal popup
src/app/fruits/home/home.component.html:
<div class="container">
  <div class="row mt-2">
    <div class="col col-md-4">
      <a class="btn btn-primary" routerLink="/add">Create</a>
    </div>
    <div class="col col-md-6 offset-md-2">
      <div class="input-group mb-3">
        <input
          type="text"
          class="form-control"
          [(ngModel)]="searchName"
          placeholder="Search By Name"
          aria-label="Recipient's username"
          aria-describedby="button-addon2"
        />
        <button
          class="btn btn-outline-primary"
          (click)="search()"
          type="button"
          id="btnsearch"
        >
          Search
        </button>
      </div>
    </div>
  </div>
  <table class="table">
    <thead>
      <tr>
        <th scope="col">Id</th>
        <th scope="col">Name</th>
        <th scope="col">Quantity</th>
        <th scope="col">Price</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let item of allFruits$ | async">
        <th scope="row">{{ item.id }}</th>
        <td>{{ item.name }}</td>
        <td>{{ item.quantity }}</td>
        <td>{{ item.price }}</td>
        <td>
          <a class="btn btn-primary" [routerLink]="['edit', item.id]">Edit</a> |
          <button
            type="button"
            (click)="openDeleteModal(item.id)"
            class="btn btn-danger"
          >
            Delete
          </button>
        </td>
      </tr>
    </tbody>
  </table>
</div>

<!-- Modal -->
<div
  class="modal fade"
  id="deleteModal"
  tabindex="-1"
  aria-labelledby="exampleModalLabel"
  aria-hidden="true"
>
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Warning!</h5>
        <button
          type="button"
          class="btn-close"
          data-bs-dismiss="modal"
          aria-label="Close"
        ></button>
      </div>
      <div class="modal-body">Are you sure to delete the item?</div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          Close
        </button>
        <button type="button" class="btn btn-danger" (click)="delete()">
          Confirm Delete
        </button>
      </div>
    </div>
  </div>
</div>
  • (Line: 44-50) Added the 'Delete' button registered the click event with 'openDeleteModal()'.
  • (Line: 58-87) Bootstrap Modal HTML.
  • (Line: 81-83) Added the 'Confirm Delete' button registered the click event with 'delet()'.

Support Me!
Buy Me A Coffee PayPal Me

Wrapping Up:

Hopefully, I think this article delivered some useful information on the Angular 14 CRUD sample by consuming the GraphQL endpoint using the Angular Apollo library. using I love to have your feedback, suggestions, and better techniques in the comment section below.

Video Session:

Refer:

Follow Me:

Comments

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