Angular2 - 检测组件子变量

时间:2016-07-14 11:56:55

标签: angular components code-injection

父组件

import { Component, OnChange } from '@angular/core';
import { ChildComponent } from '../../reusable/user-offers/user-offers.component';
@Component({
  ...
  directives: [ ChildComponent ]
})
export class ParentComponent implements OnChange {
  @ViewChild(ChildComponent)
    private child: ChildComponent;

  ngOnChanges() {
    detecting this.child.detectme variable...
  }

}

子组件

import { Component, Input } from '@angular/core';
@Component({
  ...
})
export class ParentComponent {    
  @Input() detectme: string;
  //in view something changes detectme value (not important here)
}

如何检测child.detectme是否已更改并打印其值?

1 个答案:

答案 0 :(得分:2)

您想在父组件中检测到子组件中的值发生了变化,对吗?如果是这样,您应该在子组件中使用EventEmitter并发出事件。然后使用(eventNameFromChild)="handler($event)"语法订阅父组件中的事件。

为您创建plunk