首页 > 解决方案 > 在新的浏览器窗口中打开角度模板参考

问题描述

所以这里是我面临的问题的解释。它可能看起来与其他已经提出的问题非常相似,但没有一个回答我的问题。

我想在新的浏览器窗口(包含所有样式)中打开一个角度模板引用,并使用该窗口使用系统打印对话框打印内容。

模板引用是指整个组件,或者可能只是给定组件模板的一部分。

请注意,我不想通过以下方法做到这一点:

  1. 在新的浏览器窗口中打开新路线。(为什么?这将导致所有其他事情,例如公共工具栏或帮助打开组件。还需要一条不希望的新路线。)
  2. 以可关闭的模式打开内容。

标签: htmlangularangular-components

解决方案


好的,这就是我使用ComponentFactoryResolverand的方式Injector。只需将这两个依赖项注入您想要ReportComponent在新浏览器窗口中打开其他组件(在本例中)的组件中。

构造函数在下面的代码片段中看起来像这样。

  constructor(
    private resolver: ComponentFactoryResolver,
    private injector: Injector
  ) {}

. . .

此方法在新的浏览器窗口中打开组件。

public openPrintableReport(): void {

// resolve and instantiate the component which you want to open in new window. 
const componentFactory = this.resolver.resolveComponentFactory(ReportComponent);
let component = componentFactory.create(this.injector);
component.changeDetectorRef.detectChanges();

// define external window
this.externalWindow = window.open('', '', 'width=1000,height=1000,left=150,top=200');

// copy all the styles to external window.
document.querySelectorAll('style').forEach(htmlElement => {
  this.externalWindow.document.head.appendChild(htmlElement.cloneNode(true));
});

this.externalWindow.document.title = 'Printer Friendly Report';

// attach the component to external window
this.externalWindow.document.body.appendChild(component.location.nativeElement);
}

推荐阅读