Ejecuto la aplicación Angular 9 y estoy integrando la funcionalidad de impresión mediante la creación dinámica de componentes. La funcionalidad de impresión funciona como se esperaba, pero las propiedades css de los archivos print-report.component.scss no se aplican cuando se abre la ventana de impresión.
imprimir.servicio.ts
@Injectable() export class PrintService { constructor( private componentFactoryResolver: ComponentFactoryResolver, private injector: Injector ) { } showDialog(component) { const factory = this.componentFactoryResolver.resolveComponentFactory(component); const dialogComponentRef = factory.create(this.injector); dialogComponentRef.instance.title = 'Print page'; dialogComponentRef.changeDetectorRef.detectChanges(); //fetch the root DOM element of ModalComponent const domElement = (dialogComponentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement; const WindowPrt = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto'); WindowPrt.document.write(domElement.innerHTML); WindowPrt.document.close(); WindowPrt.focus(); WindowPrt.print(); WindowPrt.close(); } }imprimir-informe.componente.ts
@Component({ selector: 'app-print-report', templateUrl: './print-report.component.html', styleUrls: ['./print-report.component.scss'], encapsulation: ViewEncapsulation.None }) export class PrintReportComponent { @Input() title: string; }imprimir-informe.componente.html
<div class="name">{{title}}</div>imprimir-informe.componente.scss
.name { // these styles are not getting applied when print window opens color: red; font-weight: bold; }mi-componente-personalizado.ts
constructor(private printService: PrintService){} onButtonClick(){ this.printService.showDialog(PrintReportComponent); }El problema aquí es que está agregando al nuevo documento solo el HTML. La solución más rápida debería ser
showDialog(component) { const factory = this.componentFactoryResolver.resolveComponentFactory(component); const dialogComponentRef = factory.create(this.injector); dialogComponentRef.changeDetectorRef.detectChanges(); //fetch the root DOM element of ModalComponent const domElement = (dialogComponentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement; const WindowPrt = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto'); WindowPrt.document.head.innerHTML = document.head.innerHTML; WindowPrt.document.body.innerHTML = domElement.outerHTML; WindowPrt.document.close(); WindowPrt.focus(); WindowPrt.print(); WindowPrt.close(); }La mejor solución debería ser leer el archivo css del componente y agregarlo al encabezado.