How can I print a single component in Angular?

15,531

The styles in the component CSS will only apply to that individual component, which is why the parent component mat tabs are still showing.

As an alternative, you can add the styles into style.css / styles.scss. The problem with this is that the parent DOM elements (such as body) will be set to display: none as well, so nothing will be visible.

You can instead try using visibility in styles.css like so:

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

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

Depending on your use case, this may help, although the hidden elements will still take up space on the page.

Here is a fork of the StackBlitz to demonstrate

Share:
15,531
gh0st
Author by

gh0st

I'm a CS graduate from CSU Sacramento with a concentration in Information Security. I'm eager to learn and share what knowledge I have.

Updated on June 13, 2022

Comments

  • gh0st
    gh0st about 2 years

    In a single angular component I wish have a print button which when the user clicks, will print a single div from my component's template.

    I know this answer works, I've tried it. But I do not like how I need to reapply all styles or rewrite all the styles in the <style> head tags.

    I really like this answer but I can't get it to work. I think it might have something to do with how classes are renamed after the app has been served/built.

    This is how I've implemented the above answer but can't get it to work.

    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;
      }
    }
    

    How can I get the above answer to work resulting as little code as possible, and retaining the styles applied to the front-end?

    I realize how similar the question is to this one but this question was asked almost two years ago and with regards to angular 2. Not quite sure how different it is with regards to angular 6.

  • Unknown User
    Unknown User over 4 years
    I tried to add a table and it doesn't work, any idea? stackblitz.com/edit/angular-pmysdr-svmhde?file=app/print-me/‌​…