I am currently working on an Angular 9 application and I have successfully implemented a print functionality by creating components dynamically. However, I have encountered an issue where the CSS properties defined in the print-report.component.scss file are not being applied 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 { // the styles below are not being applied correctly when print window opens
color: red;
font-weight: bold;
}
my-custom-component.ts
constructor(private printService: PrintService){}
onButtonClick(){
this.printService.showDialog(PrintReportComponent);
}