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

问题描述 投票:9回答:1

鉴于以下组件:

@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");
    }
}

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

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

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

谢谢

angular typescript angular2-template angular2-directives
1个回答
8
投票

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

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

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

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

Manual change detection

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

@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。在这种情况下,一种方法是在ngDoCheckCompB钩子中进行手动检查:

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();
      }
    }
}

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

© www.soinside.com 2019 - 2024. All rights reserved.