1
私は、数量を増減するボタン付きの数量構成要素&を持っています。である私は何をする必要があり、<quantity-component>
内部のプライベート値を大きくして、私は<item-component>
からaddToCart()
を呼び出すとき、私は<quantity-component>
角度2の入れ子になったコンポーネントから値を取得するにはどうすればよいですか?
内の数量値これは可能ですが取得できるようにする必要がありますか? を可能な限り使用しないようにしたいのですが、それは単に1の値を追跡するためだけに使用されるからです。
//item.component.ts
import { Component, ViewChild } from '@angular/core';
import { QuantityComponent } from './subcomponents/quantity.component/quantity.component'
@Component({
selector: 'item-component',
entryComponents: [ QuantityComponent ],
templateUrl: 'store.item.component.pug',
providers: [ QuantityComponent],
})
export class ItemComponent {
items:StoreItem[] = [];
@ViewChild(QuantityComponent)
constructor(private storeItemList: StoreItemsList, private quantityComponent: QuantityComponent) {
console.info("item component")
}
addToCart(index){
//THIS ONLY RETURNS 1 EVEN AFTER INCREASING THE QUANTITY VIA increase()
console.log(this.quantityComponent.getQuantity());
console.log('add to cart');
}
}
//quantity.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'quantity-component',
styleUrls:['quantity.component.css'],
templateUrl: 'quantity.component.pug'
})
export class QuantityComponent{
@Input() item: string;
public quantity:number = 1;
constructor() {}
increase(){
this.quantity++;
}
decrease(){
if(this.quantity>0){
this.quantity--;
}else{
this.quantity = 0;
}
}
getQuantity(){
console.log(this.quantity);
return this.quantity;
}
}
EvenEmitterで行く、チェックアウト:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#child-to-parent –
私はしかし子供のイベントを聞いていない。親イベントが発生すると、子供から価値を得る必要があります。 –