【问题标题】:angular 2 re-render parent component from @ViewChild Componentangular 2 从@ViewChild Component 重新渲染父组件
【发布时间】:2017-09-25 17:54:02
【问题描述】:

我正在开发 angular2 应用程序,其中我的父组件会弹出一个子组件

@ViewChild(childPopupComponent) case: childPopupComponent;

我想要做的是:当从子组件(在父组件内弹出)按下保存按钮时,重新渲染父组件以进行反射(而不是重新加载整个页面)。

我知道这会重新渲染当前组件,但是如何从 @ViewChild一个

this.ref.detectChanges();

【问题讨论】:

    标签: angular viewchild


    【解决方案1】:

    在您的子组件中注入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) {}
    

    【讨论】:

    • 非常感谢,如果我想将整个父组件注入子组件中以便从子组件调用父函数.. 我该怎么做,因为它会抛出奇怪的错误不能解析 casePopupComponent 的所有参数:([object Object], [object Object], [object Object], [object Object], [object Object], [object Object], ?)
    • ? 通常发生在循环依赖中。您可以提供抽象类来解决它stackoverflow.com/questions/43198098/…
    • 另一个解决方案是在您的子组件和父模板中使用@Ouput 事件,只需订阅它<child (somethingChanged)="onHandleWithParentMethod()" 这样您就不需要解决循环依赖问题
    • 谢谢yurzui,很有用
    猜你喜欢
    • 2018-08-12
    • 2019-06-01
    • 2020-09-19
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    相关资源
    最近更新 更多