首页 文章

父/子组件交互 - 使用EventEmitter angular2返回值

提问于
浏览
0

1)我有一个使用@Output 2发出事件的子组件(CounterComponent) . 子组件也有一个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);

}

有人可以帮忙吗?

1 回答

  • 0

    实际上,这个 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 仍未定义 . 有几种方法可以让它发挥作用 .

    • 服务

    • 工具 ngOnChanges()

    以下是后者的一个例子:

相关问题