为什么angular 2 ngOnChanges不响应输入数组推送 [英] Why angular 2 ngOnChanges not responding to input array push
问题描述
我的角度应用程序遇到了问题,我使用输入作为数组,并在发生click事件时将值推入数组.但是在完成数组推送后,ngOnChanges不会触发.有没有办法触发ngOnChange
My angular application stuck with a issue, i used input as array and pushed a value to the array when the click event arise. But the ngOnChanges not firing when the array push is done. Is there a way to fire ngOnChange
我的代码是ts文件是
@Component({
selector: 'adv-search',
templateUrl: './app/modules/result.html'
})
export class InputComponent {
@Input() metas:any=[];
ngOnChanges() {
console.log(this.metas);
}
}
我的选择器标记
<adv-search [metas] = "metaIds"></adv-search>
点击事件代码
insertIds(id:any) {
metaIds.push(id);
}
推荐答案
角度变化检测仅检查对象身份,而不检查对象内容. 因此,未检测到插入或删除.
Angular change detection only checks object identity, not object content. Inserts or removals are therefore not detected.
您可以做的是在每次更新后复制阵列
What you can do is to copy the array after each update
insertIds(id:any) {
this.metaIds.push(id);
this.metaIds = this.metaIds.slice();
}
或使用IterableDiffer
像NgFor
一样检查ngDoCheck
中InputComponent
内部的变化.
or use IterableDiffer
to check for changes inside InputComponent
in ngDoCheck
like NgFor
does.
这篇关于为什么angular 2 ngOnChanges不响应输入数组推送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!