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

问题描述 投票:1回答:1

我有一个项目组件和一个数量组件,其中包含增加和减少数量的按钮。我需要做的是,在<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;
    }

}
angular
1个回答
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');
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.