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

查看:27
本文介绍了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 Lifecycle Hook 仅在输入属性的实例更改时触发.

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

如果要检查输入数组中的元素是否被添加、移动或删除,可以使用DoCheck 生命周期钩子内的 >IterableDiffers 如下:

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 = 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天全站免登陆