1

在我的主视图中,我注入了一个组件,在初始加载时,它显示了正确的整数,但如果我稍后在主视图中更新该值,附加到函数的控制台日志消息显示正确的整数,但实际的 html 值确实不更新。这里发生了什么?

主.js:

@Component({
    selector: 'step-one',
    directives: [priceBox],
    templateUrl: 'step-one/step-one.html'
})

export class stepOne {

    constructor(@Inject(Router) router, @Inject(Http) http, @Inject(RouteParams) params, @Inject(priceBox) pbox) {
        let cid = parseInt(params.get('country'));

        pbox.price = 200;

        ...

price-box.js

import {Component} from 'angular2/core';

@Component({
    selector: 'price-box',
    template: `
        <div>
            <h1>PRICEBOX</h1>
            <p>{{totalPrice}}</p>
        </div>
        `
})

export class priceBox {
    constructor() {
        this.totalPrice = '130';
    }

    set price(val){
        this.totalPrice = val;
        console.log('SET price box: price = ' + this.totalPrice);
    }
}

所以重申一下:在加载页面时,我的价格框元素显示价格为 130...当我尝试通过该值设置新值时,pbox.price = 200 该值保持在 130但我收到控制台日志消息说SET price box: price = 200

谢谢!

4

1 回答 1

2

将子组件 ( priceBox) 注入父组件的方式有点奇怪。

如果要在父组件中引用组件,则应利用ViewChild装饰器:

@Component({
  selector: 'someDir',
  templateUrl: 'someTemplate',
  directives: [ItemDirective]
})
class stepOne {
  @ViewChild(ItemDirective) viewChild:priceBox;
  ngAfterViewInit() {
    // viewChild is set
  }

}

我还可以使用插值为您的 priceBox 组件提供价格。后者定义了一个输入参数:

@Component({
  selector: 'price-box',
  template: `
      <div>
          <h1>PRICEBOX</h1>
          <p>{{totalPrice}}</p>
      </div>
      `
})
export class priceBox {
  @Input('val') totalPrice = '130';
}

您可以从父组件中使用它:

@Component({
  selector: 'price-box',
  template: `
    <price-box [val]="price"></price-box>
  `
})
export class stepOne {
  price = '200';
}

您会注意到,您还可以利用自定义组件的两种方式绑定。你只需要添加一个相应的事件:

@Component({
  selector: 'price-box',
  template: `
      <div>
          <h1>PRICEBOX</h1>
          <p>{{totalPrice}}</p>
      </div>
      `
})
export class priceBox {
  @Input('val') totalPrice = '130';
  @Output('valChanged') totalPriceChanged:EventEmitter;

  constructor() {
    this.totalPriceChanged:EventEmitter = new EventEmitter();
  }

  updateTotalPrice() {
    this.totalPriceChanged.emit(this.totalPrice);
  }
}

现在在父组件中:

@Component({
  selector: 'price-box',
  template: `
    <price-box [(val)]="price"></price-box>
  `
})
export class stepOne {
  price = '200';
}

希望它可以帮助你,蒂埃里

于 2016-01-27T11:25:36.513 回答