如何从Angular 2中的嵌套组件中获取值?

时间:2016-10-25 18:28:18

标签: angular

我有一个项目组件&amp;带有按钮的数量组件,用于增加和减少数量。我需要做的是,在<quantity-component>内增加私有值,当我从addToCart()调用<item-component>时,我需要能够在<quantity-component>内获取数量值

这可能吗?我希望避免使用服务,只是因为它只会用于跟踪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;
    }

}

1 个答案:

答案 0 :(得分:0)

我想知道你的应用程序是如何编译的。组件和其他指令不是通过构造函数参数注入的,而是在模块中声明的。 @ViewChild只是一个装饰者,其成员就像其他任何人一样。我修复了你的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');
    }

}