Issue
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?
Solution
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);
}
}
Answered By - Selaka Nanayakkara
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.