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

sua*_*uat 16 typescript angular2-directives angular2-template angular

鉴于以下组件:

@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");
    }
}
Run Code Online (Sandbox Code Playgroud)

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

目前,我所做的是通过链接实现ngOnInitfor方法CompB并在方法内调用该方法.故事的另一部分是我的实际来源有像我想在每个渲染中重置的对象.我不确定重新渲染重置.目前,我正在重置它们的方法.updateItemViewChildsomeArraysomeArrayngOnInit

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

谢谢

Max*_*kyi 14

据我所知,除非更改完整的项目对象,否则angular2无法识别项目的更改.

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

然后,使子组件即CompB重新渲染,就像角度检测到常规方式的变化一样.

您不必特别做任何事情,因为您仍将在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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

除非你使用ChangeDetectionStrategy.OnPush.在这种情况下路要走你会做手工检查中ngDoCheck的钩CompB:

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();
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

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