2016-10-25 5 views
1

У меня есть компонент товара & количественный компонент с кнопками, которые увеличивают и уменьшают количество. Что мне нужно сделать, это, увеличить приватное значение внутри <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; 
    } 

} 
+0

Go с EvenEmitter, проверьте: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#child-to-parent –

+0

I Однако я не слушал дочернее событие. Мне нужно получить значение от ребенка, когда происходит родительское событие. –

ответ

0

Мне интересно, как ваше приложение компилируется вообще. Компоненты и другие директивы не вводятся через параметры конструктора, а объявляются в вашем модуле. @ViewChild ist только декоратор, и член действует как любой другой. Я установил свой ItemComponent:

export class ItemComponent { 

    @ViewChild(QuantityComponent) quantityComponent; // gets bound to QantityComponent by decorator 

    constructor() { 
     console.info("item component") 
    } 

    addToCart(index){ 
     this.quantityComponent.increase(); 
     console.log(this.quantityComponent.getQuantity()); // 2, 3, 4 
     console.log('add to cart'); 
    } 

}