I have running Angular 9 application and I am integrating print functionality by dynamically creating component. The print functionality works as expected but the css properties of print-report.component.scss files are not getting applied on when the print window opens.
print.service.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();
}
}
print-report.component.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;
}
print-report.component.html
<div class="name">{{title}}</div>
print-report.component.scss
.name { // these styles are not getting applied when print window opens
color: red;
font-weight: bold;
}
my-custom-component.ts
constructor(private printService: PrintService){}
onButtonClick(){
this.printService.showDialog(PrintReportComponent);
}
The problem here is that you are adding to the new document just the HTML. The faster solution should be
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();
}
The better solution should be read the component css file and add it to the head.