Home / Angular / Understanding Event Binding in Angular 18 with a Shopping Cart Application

Understanding Event Binding in Angular 18 with a Shopping Cart Application

Angular is a powerful framework for building dynamic and interactive web applications. Among its many features, event binding plays a crucial role in handling user interactions efficiently. If you’ve ever wondered how Angular connects a user action, like clicking a button, to a specific method or functionality, event binding is the answer.

In this article, we’ll explore the concept of event binding in Angular and demonstrate its application through a shopping cart project built using Angular 18 and Node.js. Along the way, we’ll also provide references for two-way data binding and property binding to give you a holistic understanding of data interaction in Angular.

Let’s get started!

What is Event Binding in Angular?

Event binding in Angular allows you to listen to and handle DOM events such as clicks, mouse movements, keyboard actions, and more. It connects a user’s interaction with a method in the component’s TypeScript file, enabling dynamic responses to user actions.

For example:

<button (click)="onAddToCart()">Add to Cart</button>

In this snippet, the click event is bound to the onAddToCart method in the corresponding component file. Whenever the button is clicked, Angular executes the method.

Syntax of Event Binding

The basic syntax for event binding is:

(<event>)="expression"

  • event: The event you want to listen to (e.g., click, input, mouseover).
  • expression: The method or statement to execute when the event occurs.

Types of Events in Angular

  1. Mouse Events: click, dblclick, mousedown, mouseup, mouseenter, mouseleave
  2. Keyboard Events: keydown, keyup, keypress
  3. Form Events: submit, focus, blur
  4. Input Events: input, change
  5. Touch Events: touchstart, touchend, touchmove

These events enable developers to create rich and interactive user interfaces.

How Event Binding Differs from Property Binding and Data Binding

While event binding focuses on user interaction, property binding and data binding deal with the flow of data within the application.

Building a Shopping Cart Application Using Node.js and Angular 18

o demonstrate event binding, we’ll create a simple shopping cart application. This app allows users to:

  1. Add items to the cart.
  2. Remove items from the cart.
  3. Update the quantity of items.

Prerequisites

  1. Install Node.js and npm.
  2. Set up Angular CLI.
  3. Basic understanding of Angular components, services, and templates.

Step 1: Set Up the Node.js Backend

Install Dependencies

Create a new folder and run the following commands:

pm init -y
npm install express body-parser cors

Create the Backend Server

/ server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
app.use(bodyParser.json());
app.use(cors());

let products = [
  { id: 1, name: 'Product A', price: 100 },
  { id: 2, name: 'Product B', price: 150 },
  { id: 3, name: 'Product C', price: 200 },
];

let cart = [];

// Get products
app.get('/products', (req, res) => {
  res.json(products);
});

// Add to cart
app.post('/cart', (req, res) => {
  const { id, quantity } = req.body;
  const product = products.find(p => p.id === id);
  if (product) {
    cart.push({ ...product, quantity });
    res.json(cart);
  } else {
    res.status(404).send('Product not found');
  }
});

// Remove from cart
app.delete('/cart/:id', (req, res) => {
  const { id } = req.params;
  cart = cart.filter(item => item.id !== parseInt(id));
  res.json(cart);
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'

Step 2: Set Up the Angular Frontend

Generate Components

Run the following commands to create components:

ng new shopping-cart
cd shopping-cart
ng generate component product-list
ng generate component cart

Create a Service

Run:

ng generate service cart

Update the service to manage API calls:

/ cart.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class CartService {
  private apiUrl = 'http://localhost:3000';

  constructor(private http: HttpClient) {}

  getProducts(): Observable<any> {
    return this.http.get(`${this.apiUrl}/products`);
  }

  addToCart(product: any): Observable<any> {
    return this.http.post(`${this.apiUrl}/cart`, product);
  }

  removeFromCart(id: number): Observable<any> {
    return this.http.delete(`${this.apiUrl}/cart/${id}`);
  }
}

Implement Event Binding in Templates

In the ProductListComponent:

<!-- product-list.component.html -->
<div *ngFor="let product of products">
  <h3>{{ product.name }} - ${{ product.price }}</h3>
  <button (click)="addToCart(product)">Add to Cart</button>
</div>

In the CartComponent:

<!-- cart.component.html -->
<div *ngFor="let item of cart">
  <h3>{{ item.name }} - ${{ item.price }} x {{ item.quantity }}</h3>
  <button (click)="removeFromCart(item.id)">Remove</button>
</div>

Step 3: Add Logic to Components

In ProductListComponent:

/ product-list.component.ts
import { Component, OnInit } from '@angular/core';
import { CartService } from '../cart.service';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
})
export class ProductListComponent implements OnInit {
  products: any[] = [];

  constructor(private cartService: CartService) {}

  ngOnInit(): void {
    this.cartService.getProducts().subscribe(data => this.products = data);
  }

  addToCart(product: any): void {
    this.cartService.addToCart({ id: product.id, quantity: 1 }).subscribe();
  }
}

In CartComponent:

// cart.component.ts
import { Component, OnInit } from '@angular/core';
import { CartService } from '../cart.service';

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
})
export class CartComponent implements OnInit {
  cart: any[] = [];

  constructor(private cartService: CartService) {}

  ngOnInit(): void {
    this.cartService.getProducts().subscribe(data => this.cart = data);
  }

  removeFromCart(id: number): void {
    this.cartService.removeFromCart(id).subscribe(data => this.cart = data);
  }
}

How Event Binding Works in This Project

In this shopping cart application, event binding is used extensively to manage user interactions. For instance:

  1. Add to Cart: In the ProductListComponent, when the user clicks the “Add to Cart” button, the addToCart() method is triggered. This method interacts with the CartService to send the selected product to the backend API.
<button (click)="addToCart(product)">Add to Cart</button>
addToCart(product: any): void {
  this.cartService.addToCart({ id: product.id, quantity: 1 }).subscribe();
}

Remove from Cart: In the CartComponent, when the user clicks the “Remove” button, the removeFromCart() method is invoked. This method calls the service to delete the item from the backend and updates the UI accordingly.

<button (click)="removeFromCart(item.id)">Remove</button>
removeFromCart(id: number): void {
  this.cartService.removeFromCart(id).subscribe(data => this.cart = data);
}

By binding these events to specific methods in the components, Angular ensures that user actions are seamlessly translated into application behavior. This makes the app interactive and responsive.

Concluding Thoughts

Event binding is a cornerstone of Angular development, enabling developers to create interactive and user-friendly applications. In this project, we used event binding to manage critical actions like adding and removing items from the cart, demonstrating its practical utility.

To further enhance your skills, explore Angular’s extensive documentation and experiment with different event types. Mastering event binding, along with property and two-way data binding, will give you the tools to build dynamic, data-driven applications with ease.

Happy coding!

FAQ

Additional Resources

For further learning, check out these resources:

Scroll to Top