为什么 angular 2 ngOnChanges 不响应输入数组推送 [英] Why angular 2 ngOnChanges not responding to input array push
问题描述
我的 angular 应用程序遇到了一个问题,我使用输入作为数组,并在点击事件发生时将一个值推送到数组中.但是当数组推送完成时 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 文件是
My Code is ts file is
@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 变化检测只检查对象身份,不检查对象内容.因此不会检测到插入或删除.
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
来检查 ngDoCheck
中 InputComponent
内部的变化,就像 NgFor
所做的那样.
or use IterableDiffer
to check for changes inside InputComponent
in ngDoCheck
like NgFor
does.
这篇关于为什么 angular 2 ngOnChanges 不响应输入数组推送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!