I have a Service, PrintService that I have added to my application. The Service extracts elements from a page and renders another window with the contents of the extracted elements.
import {Injectable} from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class PrintService {
popupPrint(selector: string) {
const printContents = (document.querySelector(selector) as HTMLTableElement).innerHTML;
const popupWin = window.open('', '_blank', 'top=0,left=0,height=auto,width=auto');
popupWin?.document.open();
popupWin?.document.write(`
<html>
<head>
<title>Print tab</title>
<style>
.d-flex {
width: 100%;
display: flex;
justify-content: space-between;
}
// ... More CSS
@media print {
.d-print-none {
display: none;
}
}
</style>
</head>
<body>
<section class='d-print-none'>
<button onclick="window.print();">Print</button>
<button onclick="window.close();">Cancel</button>
</section>
${printContents}
</body>
<script>
(function() {
window.print();
})();
</script>
</html>`
);
}
constructor() {
}
}
This works. Print Service on Stackblitz
My Problem now is this, I need to be remove the css styles from the service above to its own file, How can I be able to achieve this
My initial plan was to move it to a text file and read the text file from angular but I believe there is a better approach
Edit 1
Why do I need to have this on a separate style sheet?
I am building an application on a dark theme using bootstrap css. I need to extract the table and print it on a light theme. I think users would prefer to print a black text on white background.
I have a PrintComponent
@Component({
selector: 'app-print',
templateUrl: './print.component.html',
styleUrls: ['./print.component.less']
})
export class PrintComponent {
@Input() selector: string;
constructor(private printService: PrintService) {
}
print(): void {
this.printService.popupPrint(this.selector);
}
And Html is just a button
<button class="btn btn-secondary btn-sm" (click)='print()' type="button">
Print <span class="icon-print"></span>
</button>
The Idea is to a simple way to print any item on a page e.g I can have
<app-print selector='#reportTable'>
<table id='reportTable'>
<!-- Contents of this table will be extracted and displayed for printing -->
</table>
What would I consider a better approach?
Currently, my
PrintServiceis a large file. Extracting it to a different file will at least solve this problem.Next If the file can be added to the minification process, that would be great
I also hope of a way to 'lazy load' this service only when required
If possible, can I simply have a link to this stylesheet? something like
<link rel="stylesheet" href="some/print/style.css"></link>
ng-templateto define the layout and styling and use slots for entering the data as needed? There are plenty of good references on how to use templates so you can look into that.ng-templateany link to reference would be great