【问题标题】:How can I print a single component in Angular?如何在 Angular 中打印单个组件?
【发布时间】:2019-03-04 19:50:06
【问题描述】:

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

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

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

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

component.ts

onPrint() {
  window.print();
}

component.html

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

component.scss

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

我怎样才能使上述答案起作用,从而尽可能少地编写代码,并保留应用于前端的样式?

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

【问题讨论】:

  • 您能否展示您对第二种解决方案的尝试,但您说它不起作用?您将样式添加到哪个文件?
  • 当然!我已将其添加到我的问题中。
  • 当我在 StackBlitz / Chrome stackblitz.com/edit/angular-rfy6cj987654324@ 上尝试时似乎可以工作
  • 无论出于何种原因,它似乎都会打印出所有除了我的div class="print"元素。
  • 当我尝试 Stackblitz 时,打印预览中显示的唯一位是 all the stuffs I want to print

标签: angular printing report


【解决方案1】:

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

您也可以将样式添加到style.css / styles.scss。这样做的问题是父 DOM 元素(例如 body)也将设置为 display: none,因此 nothing 将是可见的。

您可以尝试在styles.css 中使用visibility,如下所示:

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

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

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

Here is a fork of the StackBlitz to demonstrate

【讨论】:

【解决方案2】:

一个简单的解决方案可能是在页面内容上显示div

@media print {
 .print {
    position: fixed;

    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
  }
}

【讨论】:

    【解决方案3】:

    对我有用的唯一方法是隐藏我正在打印的元素之外的所有元素。由于样式问题,将 HTML 复制到新窗口(和类似的解决方案)对我不起作用。

    以下代码需要 jQuery 才能工作。

    print(triggerElement): void
    {
        const toShow = this.hideParentSiblings($('#print-section'));
        $(triggerElement).hide();
    
        window.print();
    
        for (const e of toShow)
        {
            e.show();
        }
    
        $(triggerElement).show();
    }
    
    hideParentSiblings(element): any[]
    {
        let parent;
        const toShow = [];
    
        while ((parent = element.parent()).length)
        {
            const visible = parent.siblings().find(':visible');
            toShow.push(visible);
            visible.hide();
            element = parent;
        }
    
        return toShow;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-23
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 2017-10-29
      • 1970-01-01
      相关资源
      最近更新 更多