2015-09-06 103 views
2

在撰写本文时,Im使用Angular 2.0.0-alpha.36。 在下面的代码,如预期的一切功能,除了的onChange:Angular2 LifecycleEvent.onChange Not Firing

/// <reference path="../../typings-custom/_custom.d.ts" /> 

import {Component, View, LifecycleEvent} from 'angular2/angular2'; 

@Component({ 
    selector: 'counter', 
    lifecycle: [LifecycleEvent.onInit, LifecycleEvent.onChange, LifecycleEvent.onCheck, LifecycleEvent.onAllChangesDone] 
}) 
@View({ 
    template: '<button (click)="increment()">Increase Component {{count}}</button>' 
}) 

export class Counter { 

    count: number = NaN; 

    constructor() 
    { 
     this.count = 0; 
    } 

    increment() 
    { 
     ++this.count; 
    } 

    onInit() 
    { 
     console.log('onInit'); 
    } 

    onCheck() 
    { 
     console.log('onCheck'); 
    } 

    onChange(changes) 
    { 
     console.log('onChange'); 
     console.log(changes); 
    } 

    onAllChangesDone() 
    { 
     console.log('onAllChangesDone'); 
    } 
} 
从众多的堆栈溢出的搜索

除此之外,我引用的几条线,包括:

http://plnkr.co/edit/gtfY4C5mXJDhohEIVkSn?p=preview

http://learnangular2.com/lifecycle/

任何帮助,将不胜感激。

+0

[看到这个答案](http://stackoverflow.com/questions/32292620/angular2-child-directive-attribute-binding-only-seeing-initial-values)。你基本上必须改变参考,而不是价值。 –

回答

3

onChange()当组件输入绑定发生更改时被触发。

问题是Counter组件没有输入属性(输入绑定),所以这就是为什么从来没有调用onChange()事件的原因。

+0

你能否解释什么是差异。 Oninit和consturctor之间哪一个被首先调用? –

+0

构造函数被调用第一次,然后在初始化AFIK –

+0

是Oninit调用之前模板加载或加载到模板? –