如何使`ngOnChanges`在`angular2`中工作

时间:2016-03-06 05:58:28

标签: angular

我的孩子组成如下:

'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'
        };
    }

}

每次点击“更新”按钮时,都不会调用ngOnChanges方法,但为什么?

我使用的角度版本是“2.0.0-beta.8”

3 个答案:

答案 0 :(得分:14)

<强> It's working
app.ts

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'
      };
   }
};

<强> child.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);
    }
}

答案 1 :(得分:2)

它适用于&#34;输入属性&#34;,这意味着以这种格式传递的那些:@Input()myVariable:string;

当这个输入值是一个字符串,数字或布尔值时,我使它正常工作,但是对象我现在还没有发生什么。

所以,在&#34; AppComponent&#34;模板(.html)可以是这样的:

volatile

&#34;测试组件&#34;看起来像这样:

<input type="text" [(ngModel)]="name"> // name is a string property of the AppComponent
<app-test [myVal]="name"></app-test>

干杯。

答案 2 :(得分:0)

看起来您尚未实现接口OnChanges ..如果实现了OnChanges接口,则仅ngOnChanges将被视为生命周期挂钩函数,并且将调用输入更改,否则将被视为普通函数