Angular2:儿童指令属性绑定只看到初始值 [英] Angular2: Child directive attribute binding only seeing initial values

查看:325
本文介绍了Angular2:儿童指令属性绑定只看到初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件和儿童指令。在已传递到儿童整数数组通过属性事件数据

问题是,NG-for循环可以看到变化的时候,添加按钮被点击(和一个整数被添加到阵列),但的onChange 在孩子的指导作用从来没有在页面加载后再次调用。所以儿童看到数组的初始内容,但之后从不更新

 进口{NgFor,组件,景观,指令,LifecycleEvent}从'angular2 / angular2';
从angular2 /路由器的进口{routerDirectives};
进口{}注入从'angular2 / DI';@指示({
    选择:'孩子',
    生命周期:[LifecycleEvent.onChange]
    属性:['数据:事件数据']
})
出口类儿童{
    数据:数组<号取代;
    构造函数(){
    }    的onChange(变化:{IDX:字符串,PropertyUpdate}){
        如果(修改['数据']){
            的console.log(数据已更新);
        }
    }
}@零件({
    选择:父
})
@视图({
    模板:`
    <儿童[赛事数据] =eventsData>< /儿童>
    <按钮(点击)=的addValue()>添加< /按钮>    <李·纳克换=eventsData排名EV>
        {{EV}}
    < /李>
    `
    指令:[routerDirectives,儿童,NgFor]
})
出口类父{
    eventsData:数组<号取代;    构造函数(){
        this.eventsData = [10,20,30,40,50,60];
    }
    的addValue(){
        this.eventsData.push(100);
    }
}


解决方案

这里是你的修复

\r
\r

的addValue(){\r
    变种阵列= this.eventsData.slice(0); //创建数组复制\r
    的Array.push(100); //发生变异组拷贝\r
    this.eventsData =阵列; //代替REF\r
  }

\r

\r
\r

I have a Parent component and a Child directive. The Parent has an Array of integers passed to the Child through the attribute events-data.

The problem is that the ng-for loop can see the changes when the Add button is clicked (and an integer is added to the array) but the onChange function in the Child directive is never called again after the loading of the page. So the Child sees the initial content of the array but is never updated after that.

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

解决方案

here's your fix

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

这篇关于Angular2:儿童指令属性绑定只看到初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆