Angular:Child指令属性绑定仅查看初始值

时间:2015-08-30 02:33:01

标签: angular

我有一个Parent组件和一个Child指令。 Parent有一个整数数组,通过属性Child传递给events-data

问题是ng-for循环可以在单击Add按钮时看到更改(并且向数组添加了一个整数),但Child指令中的onChange函数从不加载页面后再次调用。因此,Child会看到数组的初始内容,但在此之后永远不会更新。

import {NgFor,Component,View, Directive, LifecycleEvent} from 'angular2/angular2';
import {routerDirectives} from 'angular2/router';
import {Inject} from 'angular2/di';

@Directive({
    selector:'child',
    lifecycle: [ LifecycleEvent.onChange ],
    properties: [ 'data: events-data' ]
})
export class Child{
    data: Array<number>;
    constructor() {
    }

    onChange(changes:{idx: string, PropertyUpdate}) {
        if (changes['data']) {
            console.log("DATA WAS UPDATED");
        }
    }
}

@Component({
    selector:'parent'
})
@View({
    template:`
    <child [events-data]="eventsData"></child>
    <button (click)="addValue()">Add</button>

    <li *ng-for="#ev of eventsData">
        {{ev}}
    </li>
    `,
    directives:[routerDirectives,Child,NgFor]
})
export class Parent{
    eventsData:Array<number>;

    constructor() {
        this.eventsData = [10,20,30,40,50,60];
    }
    addValue(){
        this.eventsData.push(100);
    }
}

1 个答案:

答案 0 :(得分:1)

这是您的修复

&#13;
&#13;
  addValue(){
    var array = this.eventsData.slice(0); // create array copy
    array.push(100); // mutate array copy
    this.eventsData = array; // replace ref
  }
&#13;
&#13;
&#13;