简体   繁体   中英

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?

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. Then you subscribe to the event in the parent component using (eventNameFromChild)="handler($event)" syntax.

Created a plunk for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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