角度,必须提供要附加的门户网站

时间:2019-11-08 07:39:20

标签: angular angular-cdk

我正在尝试通过一个角度的门户网站打开一个新的浏览器窗口。我遵循了这个堆叠闪电战,因为我对如何执行此操作一无所知:https://stackblitz.com/edit/angular-open-window

一个新窗口打开,但是没有显示任何内容,并且我收到错误消息:

Error: "Must provide a portal to attach"

我将门户网站导入了我的应用程序模块,所以这不是问题...

这些是我的文件:

Window.ts

import { Component, OnInit, ViewChild, ComponentFactoryResolver, ApplicationRef, Injector, OnDestroy } from '@angular/core';
import { CdkPortal, DomPortalHost } from '@angular/cdk/portal';

@Component({
  selector: 'app-preview-window',
  templateUrl: './preview-window.component.html',
  styleUrls: ['./preview-window.component.css']
})
export class PreviewWindowComponent implements OnInit, OnDestroy {

  @ViewChild(CdkPortal, {static: false}) portal: CdkPortal;
  private externalWindow = null;

  constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
    private applicationRef: ApplicationRef,
    private injector: Injector
  ) { }

  ngOnInit() {
    this.externalWindow = window.open('', '', 'width=600, height=400, left=200, top=200');

    const host = new DomPortalHost (
      this.externalWindow.document.body,
      this.componentFactoryResolver,
      this.applicationRef,
      this.injector
    );

    host.attach(this.portal);
  }

  ngOnDestroy() {
    this.externalWindow.close();
  }
}

Window.html

<ng-container *cdkPortal>
    <ng-content></ng-content>
</ng-container>

父组件html

[...]
<app-preview-window *ngIf="showWindow == true">
    <h1>Test</h1>
</app-preview-window>

0 个答案:

没有答案