角度:子指令属性绑定仅看到初始值 [英] Angular: Child directive attribute binding only seeing initial values
本文介绍了角度:子指令属性绑定仅看到初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 Parent
组件和一个 Child
指令. Parent
具有一个通过属性 events-data
传递给 Child
的整数数组.
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
.
问题在于,当单击 Add
按钮(并将一个整数添加到数组)时,ng-for循环可以看到更改,但是 onChange
函数页面加载后,再也不会再次调用Child指令中的.因此,Child会看到数组的初始内容,但此后再也不会更新.
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);
}
}
推荐答案
这是您的解决方法
addValue(){
var array = this.eventsData.slice(0); // create array copy
array.push(100); // mutate array copy
this.eventsData = array; // replace ref
}
这篇关于角度:子指令属性绑定仅看到初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文