如何手动触发更改事件 – angular2

鉴于以下组件:
@Component({
    selector: 'compA',template:  template: `<compB [item]=item></compB>`
})
export class CompA {
    item:any;
    updateItem():void {
        item[name] = "updated name";
    }
}

@Component({
    selector: 'compB',template:  template: `<p>{{item[name]}}</p>`
})
export class CompB implements OnInit{
    @input() item: any;
    someArray: any[];

    ngOnInit():void {
        someArray.push("something");
    }
}

据我所知,除非更改完整的项目对象,否则angular2无法识别项目的更改.因此,我想在调用updateItem方法时手动为项发出更改事件.然后,使子组件,即CompB重新渲染,就像角度检测到常规方式的变化一样.

目前,我所做的是为CompB实现ngOnInit方法,并通过ViewChild链接在updateItem方法调用方法.故事的另一部分是我的实际源码有像someArray这样的对象,我想在每个渲染中重置它.我不确定重新渲染是否会重置someArray.目前,我正在ngOnInit方法中重置它们.

所以,我的问题是:如何触发对父对象的更深层元素的更改进行重新渲染?

谢谢

As far as I understood that unless the complete item object is
changed,angular2 does not recognize the changes on item.

这并不是那么简单.您必须区分在对象变异时触发ngOnChanges和子组件的DOM更新. Angular无法识别该项已更改且未触发ngOnChanges生命周期钩子,但如果您引用模板中项目的特定属性,DOM仍将更新.这是因为保留了对象的引用.因此有这种行为:

And afterwards,make the child component i.e. CompB re-rendered as if
angular detected a change in the regular way.

您不必特别做任何事情,因为您仍然会在DOM中进行更新.

手动更改检测

您可以插入更改检测器并像这样触发它:

@Component({
    selector: 'compA',template:  template: `<compB [item]=item></compB>`
})
export class CompA {
    item:any;
    constructor(cd: ChangeDetectorRef) {}

    updateItem():void {
        item[name] = "updated name";
        this.cd.detectChanges();
    }
}

这会触发当前组件及其所有子组件的更改检测.

但是,它不会对你的情况产生任何影响,因为即使Angular没有检测到item中的更改,它仍会运行对子B组件的更改检测并更新DOM.

除非您使用ChangeDetectionStrategy.OnPush.在这种情况下,一种方法是在CompB的ngDoCheck钩子中进行手动检查:

import { ChangeDetectorRef } from '@angular/core';

export class CompB implements OnInit{
    @input() item: any;
    someArray: any[];
    prevIoUs;

    constructor(cd: ChangeDetectorRef) {}

    ngOnInit():void {
        this.prevIoUs = this.item.name;
        someArray.push("something");
    }

    ngDoCheck() {
      if (this.prevIoUs !== this.item.name) {
        this.cd.detectChanges();
      }
    }
}

您可以在以下文章中找到更多信息:

> Everything you need to know about change detection in Angular文章.
> The mechanics of DOM updates in Angular
> The mechanics of property bindings update in Angular

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...