skip to Main Content

I want to update cart badge value (in the navbar component) everytime user click Add to Cart button (in the product-list component).

I have a cart button in navbar component (with a badge which have the value equal to the number of products being added in the cart)

navbar.html:

<nav class="navbar fixed-top navbar-light" style="background-color: rgb(243, 208, 8);">
    <a class="navbar-brand store_title"> TeeRex Store </a>
    <a class="navbar-brand mx-auto products" routerLink="/product-list" routerLinkActive="active_route"> Products </a>
    <p-button class="nav-link ms-auto cart_btn" [badge]="cart_length" routerLink="/shopping-cart" icon="pi pi-shopping-cart" [raised]="true"></p-button>
</nav> <br>

product-list.ts:

addToCart(product: any) {
    this._data.setShoppingCartList(product); // product is being added to the shopping list
}

I want to increment the badge value (in navbar) everytime user click this Add to Cart button. I just want to know how to update the value (cart_length) in the navbar component?

2

Answers


  1. Assuming that you have two unrelated components you can use a shared service to achieve this.

    create a shared service :
    import { Injectable } from '@angular/core';
    import { BehaviorSubject } from 'rxjs';
    
    @Injectable({
      providedIn: 'root',
    })
    export class DataService {
      private dataSubject = new BehaviorSubject<string>('initial data'); // Use behavioural subject to emit data
      data$ = this.dataSubject.asObservable();
    
      updateData(newData: string) {
        this.dataSubject.next(newData); // Emit new data to the data$
      }
    }
    
    In your component A :
    import { Component, OnInit } from '@angular/core';
    import { DataService } from './data.service';
    
    @Component({
      selector: 'app-component-a',
      template: `
        <p>{{ data }}</p>
      `,
    })
    export class ComponentAComponent implements OnInit {
      data: string;
    
      constructor(private dataService: DataService) {}
    
      ngOnInit() {
        this.dataService.data$.subscribe((newData) => {
          this.data = newData; // subscribe to the latest changes in OnInit
        });
      }
    }
    
    In component B :
    import { Component } from '@angular/core';
    import { DataService } from './data.service';
    
    @Component({
      selector: 'app-component-b',
      template: `
        <button (click)="updateData()">Update Data</button>
      `,
    })
    export class ComponentBComponent {
      constructor(private dataService: DataService) {} // dependency injection of service 
    
      updateData() {
        const newData = 'new data';
        this.dataService.updateData(newData);
      }
    }
    
    Login or Signup to reply.
  2. If you want update or add, you can do like this

    Service

    import { Injectable } from '@angular/core';
    import { BehaviorSubject } from 'rxjs';
    
    @Injectable({
      providedIn: 'root',
    })
    export class DataService {
      data = new BehaviorSubject([]);
    
      addData(newData: object) {
         this.data.subscribe((items) => {
           this.data.next([...items,newData])
         })
      }
    
      updateData(newData: object) {
           this.data.subscribe((items) => {
              this.data.next(items.map((item) => item.id === newData.id ? newData: item))
           })
      }
    }
    

    Component A

    import { Component, OnInit } from '@angular/core';
    import { DataService } from './data.service';
    
    @Component({
      selector: 'app-component-a',
      template: `
        <div *ngFor="let item of dataService.data | async">{{item.name}}</div>
      `,
    })
    export class ComponentAComponent implements OnInit {
      constructor(public dataService: DataService) {}
    }
    

    Component B

    import { Component } from '@angular/core';
    import { DataService } from './data.service';
    
    @Component({
      selector: 'app-component-b',
      template: `
        <div>
          <button (click)="addData(data)">Update Data</button>
          <button (click)="updateData(data)">Update Data</button>
       </div>
      `,
    })
    export class ComponentBComponent {
      data = {id: 'dataId', name: 'dataName'}
    
      constructor(private dataService: DataService) {} // dependency injection of service 
    
      addData(data) {
        this.dataService.addData(data);
      }
    
      updateData(data) {
        this.dataService.updateData(data)
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search