I am going to create an online shopping site using angular 2. I got a cart in the navigation menu and i want to update the cart value when user add product in the cart. My can pass the value between component but can't update this value in the html template. My code example hear:-
nav.component
export class NavComponent implements OnInit {
cartItem = 5;
constructor(private cartService:CartServiceService) {
this.cartItem = this.cartService.cartItem;
}
}
nav template
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a routerLink="/">Home</a></li>
<li><a routerLink="/details">Details</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="active"><a href="./">Cart <span>{{cartItem}}</span> </a></li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container-fluid -->
</nav>
the navigation menu looks like
I got a component call home component and home component have a button. when home component click to button the Cart menu automatically will update.
home component
export class HomeComponent implements OnInit {
cartItem: number;
constructor(private cartService: CartServiceService) {
}
ngOnInit() {
}
click() {
this.cartService.cartChange.subscribe((value) => {
this.cartService.cartItem = 10;
})
}
}
And finally the service
cart service
@Injectable()
export class CartServiceService {
constructor() {
console.log(this.cartItem);
}
cartItem:number = 1;
cartChange:Subject<number> = new Subject<number>();
changeCart() {
this.cartItem = 5;
this.cartChange.next(this.cartItem);
}
}
and i call this service in the app-module
providers: [CartServiceService]
How can i update the cart in the navbar ??