【发布时间】:2020-11-04 22:48:02
【问题描述】:
我有一个服务,PrintService,已添加到我的应用程序中。服务从页面中提取元素并使用提取的元素的内容呈现另一个窗口。
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() {
}
}
这行得通。 Print Service on Stackblitz
我现在的问题是,我需要从上面的服务中删除css样式到它自己的文件中,我怎样才能做到这一点
我最初的计划是将其移动到文本文件并从角度读取文本文件,但我相信有更好的方法
编辑 1
为什么我需要将它放在单独的样式表中?
我正在使用 bootstrap css 在深色主题上构建应用程序。我需要提取表格并将其打印在浅色主题上。我认为用户更喜欢在白色背景上打印黑色文本。
我有一个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);
}
而 Html 只是一个按钮
<button class="btn btn-secondary btn-sm" (click)='print()' type="button">
Print <span class="icon-print"></span>
</button>
这个想法是一种简单的方法来打印页面上的任何项目,例如我可以拥有
<app-print selector='#reportTable'>
<table id='reportTable'>
<!-- Contents of this table will be extracted and displayed for printing -->
</table>
我认为更好的方法是什么?
-
目前,我的
PrintService是一个大文件。将其提取到不同的文件至少可以解决这个问题。 -
下一个如果可以将文件添加到缩小过程中,那就太好了
-
我还希望有一种方法可以仅在需要时“延迟加载”此服务
-
如果可能,我可以简单地提供一个指向此样式表的链接吗?类似
<link rel="stylesheet" href="some/print/style.css"></link>
【问题讨论】:
-
为什么不使用
ng-template来定义布局和样式,并根据需要使用插槽来输入数据?关于如何使用模板有很多很好的参考资料,因此您可以研究一下。 -
这里有许多不同的方法可以将样式移动到一个单独的文件中,从离谱到完全合理。因此,我鼓励您在问题中添加更多信息,即:您要解决的确切问题是什么以及为什么要提取 CSS?是否纯粹是拥有一个单独的文件,例如可以使用语法突出显示,还是有其他原因?另外,您如何确定“更好”的方法?如果新窗口异步加载样式可以吗?您在寻找原生 Angular 方法吗?你在寻找一些 Webpack 解决方案吗?等等干杯!
-
@AbrarHossain,我一直在考虑你的建议,但我似乎没有提出如何使用
ng-template实现这一目标的任何计划,任何参考链接都会很棒
标签: javascript angular