Angular 9 CDK 门户错误:必须提供要附加的门户

Jos*_*ham 3 angular-material angular angular-cdk

我在处理看似简单的事情时遇到了困难。我试图在 Angular 9 中打开一个包含一些 html 的新窗口。每次运行时,我都会看到一个窗口弹出一秒钟,然后失败并抛出以下错误:

Error: Must provide a portal to attach
    at throwNullPortalError (portal.js:23)
    at DomPortalHost.attach (portal.js:320)
    at GraphPopoutComponent.ngOnInit (graph-popout.component.ts:43)
    at callHook (core.js:4686)
    at callHooks (core.js:4650)
    at executeInitAndCheckHooks (core.js:4591)
    at refreshView (core.js:11814)
    at refreshDynamicEmbeddedViews (core.js:13154)
    at refreshView (core.js:11819)
    at refreshComponent (core.js:13229)
Run Code Online (Sandbox Code Playgroud)

在有人问之前:

  • 是的,我已将 PortalModule 包含在我的 app.module.ts 中
  • 角度 9.0.7
  • 角度/cdk、角度/材料 9.1.3
  • 我确实有嵌套模块,这会导致 PortalModule 出现问题吗?

这是我的代码供参考:

graph.component.html

.
.
.
<app-graph-popout *ngIf="openPortal">
  <h1>IT WORKS</h1>
</app-graph-popout>
Run Code Online (Sandbox Code Playgroud)

图.组件.ts

.
.
.
togglePortal() {
    this.openPortal = true;
  }
Run Code Online (Sandbox Code Playgroud)

graph-popout.component.ts

@Component({
  selector: 'app-graph-popout',
  // templateUrl: './graph-popout.component.html',
  template: `
    <ng-container *cdkPortal>
      <ng-content></ng-content>
    </ng-container>
  `


})
export class GraphPopoutComponent implements OnInit, OnDestroy {

  // STEP 1: get a reference to the portal
  @ViewChild(CdkPortal) portal: CdkPortal;

  // STEP 2: save a reference to the window so we can close it
  private externalWindow = null;

  // STEP 3: Inject all the required dependencies for a PortalHost
  constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
    private applicationRef: ApplicationRef,
    private injector: Injector) { }

  ngOnInit() {
    // STEP 4: create an external window
    this.externalWindow = window.open('', '', 'width=600,height=400,left=200,top=200');

    // STEP 5: create a PortalHost with the body of the new window document
    const host = new DomPortalHost(
      this.externalWindow.document.body,
      this.componentFactoryResolver,
      this.applicationRef,
      this.injector
    );

    // STEP 6: Attach the portal
    host.attach(this.portal);
  }

  ngOnDestroy() {
    // STEP 7: close the window when this component destroyed
    this.externalWindow.close();
  }

}
Run Code Online (Sandbox Code Playgroud)

srW*_*rks 5

面临同样的问题。按照示例 @ angular doc将代码块从 ngOnInit 移动到 ngAfterViewInit ,这解决了这个问题。

修改后的工作示例@stackblitz使用Angular 10.0.3