Angular 4.2.4 ngOnChanges不会从父组件触发

时间:2018-06-08 13:30:45

标签: angular

我正面临角度4 ngOnChange事件的奇怪问题。 ngOnChange未触发当我重置值并设置相同的值(复位前)。我想在重置(我的意思是0)值后触发ngOnChange事件。请帮助解决此问题

如下所述的工作示例和plunker链接

plunker

import { Component, NgModule, VERSION, OnInit, OnChanges, Input, Output, EventEmitter } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

@Component({
  selector: 'parent-component',
  template: `
  <button (click)="changeCountClick()">Change Count</button>
  <child-component (onCountChange)="onCountChange($event)" [count]="recordCount"></child-component>
  {{recordCount}}
  <br/>
  <br/>
  <div *ngFor="let chg of eventCalled">{{chg}}</div>
  `
})
export class ParentComponent {
  recordCount: number;
  eventCalled: string[] = [];
  constructor() { }

  ngOnInit() {
    this.recordCount = 5;
  }

  changeCountClick() {
      this.resetCount();
    this.recordCount = 5; /*Not Working*/
  //    this.recordCount = 2; /*Working*/
  }

  resetCount() {
      this.recordCount = 0;
  }

  onCountChange() {
    this.eventCalled.push('called');
  }
}

@Component({
  selector: 'child-component',
  template: ''
})
export class ChildComponent implements OnInit, OnChanges {
  @Input('count') public count: number;

  @Output() public onCountChange = new EventEmitter<number>();

  constructor() { }

  ngOnInit() {

  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes.count.currentValue !== changes.count.previousValue) {
      this.onCountChange.emit(changes.count);
    }
  }
}

0 个答案:

没有答案