简体   繁体   English

Angular2-检测组件子变量的变化

[英]Angular2 - detect component child variable change

Parent component 父组件

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...
  }

}

Child component 子组件

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

How can I detect if child.detectme changed and print it's value? 如何检测child.detectme是否已更改并打印其值?

You want to detect in parent component that the value in the child component changed, right? 您想在父组件中检测到子组件中的值已更改,对吗? If so, you should use EventEmitter in the child component and emit the event. 如果是这样,则应在子组件中使用EventEmitter并发出事件。 Then you subscribe to the event in the parent component using (eventNameFromChild)="handler($event)" syntax. 然后,使用(eventNameFromChild)="handler($event)"语法在父组件中订阅事件。

Created a plunk for you. 为您创建了一个小品

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM