用@ViewChild组件从Angular 2重新渲染父组件

3

我正在开发一个Angular2应用程序,其中有一个父组件弹出子组件。

@ViewChild(childPopupComponent) case: childPopupComponent;

我想做的是:当从父组件中弹出的子组件按下保存按钮时,重新渲染父组件以实现反映(而不是重新加载整个页面)。

我知道这会重新渲染当前组件,但如何从@ViewChild中实现呢?

this.ref.detectChanges();
1个回答

2

在您的子组件中注入ChangeDetectorRef,如下所示:

export class childPopupComponent {
    constructor(public cdRef: ChangeDetectorRef) {}

之后,您将能够仅在子组件上运行变更检测循环:

@ViewChild(childPopupComponent) case: childPopupComponent;

this.case.cdRef.detectChanges();

要更新父级元素,您可以在子元素中注入它。

export class childPopupComponent {
    constructor(public parent: ParentComponent) {}

然后

this.parent.cdRef.detectChanges()

甚至可以尝试这个:
import { ChangeDetectorRef, SkipSelf } from '@angular/core';

export class childPopupComponent {
    constructor(@SkipSelf() private parentCdRef: ChangeDetectorRef) {}

非常感谢,如果我想将整个父组件注入到子组件中以便从子组件调用父函数...由于它会抛出奇怪的错误,我该如何做?无法解析 casesPopupComponent 的所有参数:([object Object]、[object Object]、[object Object]、[object Object]、[object Object]、[object Object]、?) - sockeros
通常出现循环依赖时会出现 ?。您可以提供抽象类来解决它。https://stackoverflow.com/questions/43198098/angular2-dependency-injection-not-working-when-injected-into-a-dynamic-compone/43198716#43198716 - yurzui
另一种解决方案是在您的子组件上使用@Output事件,并在父模板中订阅它,例如<child (somethingChanged)="onHandleWithParentMethod()"。这样,您就不需要解决循环依赖的问题了。 - yurzui
谢谢yurzui,非常有用。 - sockeros

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接