[英]How can I update length of array in parent component from changing value in child component in Angular4?
I am working on e-commerce site in Angular4.I need to show a number of items present in a cart in nav bar which is written in app.component and in my product details page add to cart option is present.When a user clicks on add to cart button, a number of items showing in a cart in navbar have to be incremented.How can I implement this in Angular4?Below is my code: 我正在Angular4中的电子商务网站上工作。我需要在导航栏中显示在app.component中编写的购物车中存在的一些物品,并且在我的产品详细信息页面中存在添加到购物车选项。当用户单击时在添加到购物车按钮上,导航栏中的购物车中显示的许多商品必须增加。如何在Angular4中实现呢?下面是我的代码:
app.component.ts: if(this.storage.retrieve('cartList')==undefined){ this.storage.store('cartList',this.cartData) } else{ this.cartData=this.storage.retrieve('cartList'); } if(this.cartData){ this.length=this.cartData.length; } else{ this.length=0; } productdetails.ts: addToCart(data){ this.addCart=true; this.addedOne=false; this.hideCart=true; this.continueShopping=false; this.cartItems.push(data) this.storage.store("cartList",this.cartItems); console.log(this.cartItems.length) }
/*app.component.html:*/ <a (click)="goToCart()" style="cursor:pointer"> <h3> <div class="total"> (<span>{{this.length}}</span> items)</div> <img src="assets/images/bag.png" alt="" /> </h3> </a>
You can use @Output()
and EventEmitter
for communication between child and parent component. 您可以使用
@Output()
和EventEmitter
在子组件和父组件之间进行通信。
Child Component
import {Output,EventEmitter} from '@angular/core'
export class child{
@Output() cartLength : EventEmitter<any> = new EventEmitter();
}
emit the length whenever the products increase by this.cartLength.emit(productLength);
每当乘积增加
this.cartLength.emit(productLength);
时,发出长度this.cartLength.emit(productLength);
To Listen to the event, 要听事件,
in your parent Template, 在您的父模板中,
<child (cartLength)=cartLengthChanged($event)><child>
Define the cartLengthChanged()
in parent .ts
file : 在父
.ts
文件中定义cartLengthChanged()
:
cartLengthChanged(event){ console.log(event);//event will be data to be passed from child to parent }
In your child and parent you do a couple of things. 在孩子和父母中,您需要做几件事。
In your child component: 在您的子组件中:
@Output() updateCart: EventEmitter<any> = new EventEmitter<any>(); // before constructor
addToCart(data){
//fill carts
this.storage.store("cartList",this.cartItems);
this.updateCart.emit(true); // trigger parent
In the parent html: 在父html中:
<child (updateCart)="updateCart($event)"></child>
And in the parent component: EDIT 并在父组件中: 编辑
private updateCart(_boolean: any){
this.cartData = this.storage.retrieve('cartList');
this.length = this.cartData.length;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.