从门户网站内部{Angular CDK门户网站}分离

时间:2018-07-12 11:04:24

标签: angular angular-cdk

我正在使用Angular CDK的门户网站创建一个错误消息组件,该组件需要呈现在主体中(因此使用门户网站),然后在其他所有组件的顶部呈现。

它工作得很好,尽管在错误消息本身上,我需要能够从组件内部将其关闭。

我正在使用一项服务来设置门户并打开/隐藏消息。问题是我无法从错误消息组件本身内部调用close方法,因为那样我就具有循环依赖关系,并且所有这些依赖关系都将崩溃。

我知道您可以使用CDK的覆盖层从其组件内部引用它,是否可以对门户网站进行同样的操作,以便我可以将门户网站从错误消息组件中分离出来?

谢谢。

这是服务代码

private errorMessagePortal: ComponentPortal<ErrorMessageComponent>;
private bodyPortalHost: DomPortalHost;

constructor(
  private componentFactoryResolver: ComponentFactoryResolver,
  private appRef: ApplicationRef,
  private injector: Injector
) {
  this.errorMessagePortal = new ComponentPortal(ErrorMessageComponent);
  this.bodyPortalHost = new DomPortalHost(document.body, this.componentFactoryResolver, this.appRef, this.injector);
}

// show error message
showErrorMessage(errorMessage: ErrorMessage) {this.bodyPortalHost.attachComponentPortal(this.errorMessagePortal).instance.errorMessage = errorMessage;
}

closeErrorMessage() {
  this.bodyPortalHost.detach();
}

1 个答案:

答案 0 :(得分:1)

从Angular CDK的portal API开始:

this.errorMessagePortal.detach()

应该可以解决问题!

相关问题