Angular 2:如何检测数组中的变化? (@input属性) [英] Angular 2: How to detect changes in an array? (@input property)

查看:1234
本文介绍了Angular 2:如何检测数组中的变化? (@input属性)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用ajax请求检索对象数组的父组件。

I have a parent component that retrieves an array of objects using an ajax request.

这个组件有两个子组件:其中一个显示树中的对象结构和另一个以表格格式呈现其内容。父级通过@input属性将数组传递给子级,并且它们正确显示内容。一切都符合预期。

This component has two children components: One of them shows the objects in a tree structure and the other one renders its content in a table format. The parent passes the array to their children through an @input property and they display the content properly. Everything as expected.

当你更改对象中的某个字段时会出现问题:不会通知子组件这些更改。只有在手动将数组重新分配给变量时才会触发更改。

The problem occurs when you change some field within the objects: the child components are not notified of those changes. Changes are only triggered if you manually reassign the array to its variable.

我习惯使用Knockout JS,我需要获得类似于observableArrays的效果。

I'm used to working with Knockout JS and I need to get an effect similar to that of observableArrays.

我读过一些关于DoCheck但我不确定它是如何工作的。

I've read something about DoCheck but I'm not sure how it works.

推荐答案

OnChanges 生命周期挂钩仅在输入属性的实例更改时触发。

OnChanges Lifecycle Hook will trigger only when input property's instance changes.

如果要检查输入数组中的元素是否已添加,移动或删除,可以使用 IterableDiffers DoCheck Lifecycle Hook中如下:

If you want to check whether an element inside the input array has been added, moved or removed, you can use IterableDiffers inside the DoCheck Lifecycle Hook as follows:

constructor(private _iterableDiffers: IterableDiffers) {
    this.iterableDiffer = this._iterableDiffers.find([]).create(null);
}

ngDoCheck() {
    let changes = this.iterableDiffer.diff(this.inputArray);
    if (changes) {
        console.log('Changes detected!');
    }
}

如果需要检测数组内对象的变化,您将需要遍历所有元素,并应用 KeyValueDiffers 每个元素。 (您可以与之前的检查同时执行此操作。)

If you need to detect changes in objects inside an array, you will need to iterate through all elements, and apply KeyValueDiffers for each element. (You can do this in parallel with previous check).

访问此帖子以获取更多信息:检测Angular2中数组内对象的变化

Visit this post for more information: Detect changes in objects inside array in Angular2

这篇关于Angular 2:如何检测数组中的变化? (@input属性)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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