在DoCheck之后无法通过角度检测Angular 2输入属性更改 [英] Angular 2 input propery changes is not detect by angular after DoCheck

查看:52
本文介绍了在DoCheck之后无法通过角度检测Angular 2输入属性更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用DoCheck来检测从ngFor传递过来的输入属性中的重要变化.它正常工作.但是,当我进行了一些更改(从ngFor迭代的数组中删除一项)后,我的子组件看不到任何更改,也没有重新呈现自己.

I use DoCheck for detecting important changes in my input property that passed from ngFor. It's works normally. But when I did some changes (remove one item from array that iterate by ngFor) my child component don't see any changes and not re-render itself.

也许我做错了什么?

 ngDoCheck() {
    console.log('zz');
    var changes = this._differ.diff(this.schedulerData);
    console.log(changes);
    if(changes) {
        changes.forEachAddedItem(r => {
            console.log(r);
            if (r.key === 'tasks') this.launchScheduler();
        });
    }
}

ngOnInit() {
        console.log(this.schedulerData);

    }  /* !ngOnInit */


ngOnChanges(changes: {[propertyName: string]: SimpleChange}) {

    for (let propName in changes) {
     if (propName === 'schedulerData') {
console.log(changes[propName]);

     }
    }
}

推荐答案

默认情况下,但当对象引用发生更改时,更改检测不会检测到对象或数组中的更新.

Change detection doesn't detect updates within objects or arrays by default but when object references change.

如果您想绕过此行为,则像执行操作一样使用 ngDoCheck 是正确的方法.就您而言,这是正常行为:

If you want to bypass this behavior, using ngDoCheck like you do is the right approach. In your case, it's the normal behavior:

  • 您可以利用 IterableDiffers 类从ngDoCheck方法监听数组更新
  • ngOnChanges 方法未调用,因为它是由默认更改检测器(检测对象引用更改)触发的.
  • You listen to array update from the ngDoCheck method leveraging the IterableDiffers class
  • The ngOnChanges method isn't called since it's triggered by the default change detector (that detects object reference changes).

否则,请提供有关文档的信息:

Otherwise for your information from the doc:

请注意,指令通常不应同时使用DoCheck和OnChanges来响应同一输入上的更改.当默认的更改检测器检测到更改时,将继续调用ngOnChanges,因此通常不必在两个挂钩中都响应同一输入上的更改.必须在ngDoCheck回调中处理对更改的反应.

Note that a directive typically should not use both DoCheck and OnChanges to respond to changes on the same input. ngOnChanges will continue to be called when the default change detector detects changes, so it is usually unnecessary to respond to changes on the same input in both hooks. Reaction to the changes have to be handled from within the ngDoCheck callback.

这篇关于在DoCheck之后无法通过角度检测Angular 2输入属性更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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