2015-09-06 158 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調用之前模板加載或加載到模板? –