我的子组件如下:

'use strict';

import {Component, Input, OnInit, OnChanges, ChangeDetectionStrategy, ElementRef} from 'angular2/core';

@Component({
    changeDetection: ChangeDetectionStrategy.OnPush,
    selector: 'my-app',
    template: ''
})
export class MyApp implements OnInit {

    @Input() options: any;

    constructor(private el: ElementRef) {
    }

    ngOnInit() {

    }

    ngOnChanges(...args: any[]) {
        console.log('changing', args);
    }

}

父组件如下:
'use strict';

import {Component, Input} from 'angular2/core';
import {MyApp} from './MyApp';

@Component({
    selector: 'map-presentation',
    template: `<my-app [options]="opts"></my-app>
    <button (click)="updates($event)">UPDATES</button>
    `,
    directives: [MyApp]
})
export class MainApp {

    opts: any;

    constructor() {
        this.opts = {
            width: 500,
            height: 600
        };
    }

    updates() {
        console.log('before changes');
        this.opts = {
            name: 'nanfeng'
        };
    }

}

每次我单击“updates”按钮时,ngOnChanges方法都不会被调用,但为什么?
我使用的角度版本是“2.0.0-beta.8”

最佳答案

It's working
应用程序。

import {Component} from 'angular2/core';
import {child} from 'src/child';
@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <child-cmp [options]="opts"></child-cmp>
    <button (click)="updates($event)">UPDATES</button>
  `,
    directives: [child]
})
export class App {
   opts: any;

   constructor() {
      this.opts = {
          width: 500,
          height: 600
      };
   }

   updates() {
      console.log('after changes');
      this.opts = {
          name: 'micronyks'
      };
   }
};

儿童TS
import {Input,Component,Output,EventEmitter} from 'angular2/core';
import {Component, Input, OnInit, OnChanges, ChangeDetectionStrategy, ElementRef} from 'angular2/core';
@Component({
    selector: 'child-cmp',
    changeDetection: ChangeDetectionStrategy.OnPush,
    template: `

    `
})
export class child   {
    @Input() options: any;

    ngOnChanges(...args: any[]) {
        console.log('onChange fired');
        console.log('changing', args);
    }
}

关于angular - 如何在Angular2中使ngOnChanges工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35823698/

10-10 07:41