【问题标题】:Parent/Child Component Interaction - Return values using EventEmitter angular2父/子组件交互 - 使用 EventEmitter angular2 返回值
【发布时间】:2017-12-01 00:21:06
【问题描述】:

1) 我有一个子组件 (CounterComponent),它使用 @Output 发出事件 2)子组件还有一个Input参数callBackCancelled。 3) 父组件 (AppComponent) 将 callBackCancelled 值设置为“true”,但在子组件中该值仍未定义。

查看 plunker 示例 https://plnkr.co/edit/2vnTUEDyBKT59GDTvkEJ

callbackFunction(e) {
alert('emitting event from child callback button component');
this.callback.emit(e);

alert('Now in child component, this value should be true, but it is:  ' + this.callBackCancelled);

}

有人可以帮忙吗?

【问题讨论】:

  • this.callBackCancelled 将在 ngOnChanges 生命周期挂钩处为真。而且由于您没有“callBackCancelled”的输出,因此您应该这样使用它: [callBackCancelled] 不带括号。

标签: angular eventemitter


【解决方案1】:

实际上,这个alert('Now in child component, this value should be true, but it is: ' + this.callBackCancelled); 在下面被调用:

btncallback(event) {
    console.log(event);
    this.callBackCancelled = event;
    alert('Parent component sets the callBackCancelled value to true.');
  }

所以到那时,this.callBackCancelled 仍然未定义。有几种方法可以让它发挥作用。

  1. 一项服务
  2. 实现ngOnChanges()

这是后者的一个例子:

  1. [(callBackCancelled)] 中删除()
  2. 实现以下功能:https://plnkr.co/edit/qDG0dK01USbN1ifVFXvl?p=info

【讨论】:

    猜你喜欢
    • 2018-02-20
    • 2017-04-21
    • 2016-10-28
    • 1970-01-01
    • 2017-02-05
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    相关资源
    最近更新 更多