gpt4 book ai didi

angular - 如何在 Angular 中打印单个组件?

转载 作者:行者123 更新时间:2023-12-02 00:58:22 25 4
gpt4 key购买 nike

在单个 Angular 组件中,我希望有一个打印按钮,当用户单击该按钮时,将打印一个 div从我的组件模板。

我知道 this答案有效,我试过了。但我不喜欢我需要重新应用所有样式或重写 <style> 中的所有样式。头标签。

我真的很喜欢this回答但我无法让它工作。我认为这可能与在提供/构建应用程序后如何重命名类有关。

这就是我实现上述答案但无法使其工作的方式。

组件.ts

onPrint() {
window.print();
}

组件.html
<div class="print">
<button (click)="onPrint()">Print</button>
all the stuffs I want to print
</div>

组件.scss
@media print {
:not(.print) {
display: none !important;
}
}

我怎样才能得到上面的答案以产生尽可能少的代码,并保留应用于前端的样式?

我意识到这个问题与 this 有多么相似一个,但这个问题是在大约两年前提出的,关于 Angular 2。不太确定它与 Angular 6 有多大不同。

最佳答案

组件 CSS 中的样式仅适用于该单个组件,这就是父组件 mat 选项卡仍显示的原因。

作为替代方案,您可以将样式添加到 style.css 中。/styles.scss .这样做的问题是父 DOM 元素(例如 body )将设置为 display: none同样,所以什么都看不到。

您可以尝试使用 visibilitystyles.css像这样:

@media print {
:not(.printMe) {
visibility: hidden;
}
}

@media print {
.printMe {
visibility: visible
}
}

根据您的用例,这可能会有所帮助,尽管 hidden元素仍会占用页面空间。

Here is a fork of the StackBlitz to demonstrate

关于angular - 如何在 Angular 中打印单个组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52561686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com