У меня есть компонент товара & количественный компонент с кнопками, которые увеличивают и уменьшают количество. Что мне нужно сделать, это, увеличить приватное значение внутри <quantity-component>
и когда я призываю addToCart()
из <item-component>
мне нужно, чтобы иметь возможность получить значение количества внутри <quantity-component>
Как получить значение от вложенного компонента в Angular 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;
}
}
Go с EvenEmitter, проверьте: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#child-to-parent –
I Однако я не слушал дочернее событие. Мне нужно получить значение от ребенка, когда происходит родительское событие. –