在新浏览器中打开 angular 模板引用 window

Open an angular template reference in a new browser window

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

我想在新浏览器 window 中打开一个 angular 模板引用(包含所有样式)并使用该 window 通过系统打印对话框打印内容。

我所说的模板引用是指整个组件,也可能只是给定组件模板的一小部分。

请注意,我不想通过以下方法进行操作:

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

好的,这就是我使用 ComponentFactoryResolverInjector 完成的方法。只需将这两个依赖项注入要在新浏览器 window.

中打开其他组件(在本例中为 ReportComponent)的组件中

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

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

。 . .

此方法在新浏览器中打开组件 window。

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);
}