0

i have been looking around and i see that there is a lot of people with the same problem but so far no solution.

i´m working with angular 5 and angular material in a E-learning application for students and one of the function i need to implement is for printing the document, but i have not found a way to do it, if there is any way to print the content of a div in angular, because i try with this solution but doesn´t work, because when i get the innerHTML of the DOM Element, return me the html with angular the code:

                      <!--bindings={
  "ng-reflect-ng-for-of": "[object Object],[object Object"
}--><article _ngcontent-c18="" class="ng-tns-c18-3 ng-star-inserted" style="">

                        <!--bindings={
  "ng-reflect-ng-if": "false"
}-->


                        <!--bindings={
  "ng-reflect-ng-if": "false"
}-->


                        <!--bindings={
  "ng-reflect-ng-if": "true"
}--><p _ngcontent-c18="" autocorrect="off" draggable="return false;" oncut="return false" ondragover="return false;" ondrop="return false;" onkeypress="return false" onpaste="false" spellcheck="false" class="ng-tns-c18-3 ng-star-inserted" ng-reflect-ng-class="[object Object]" data-block-id="8f5b8d8f-9027-4c40-b7fe-d5ec90334fd9" contenteditable="true">Hallo Zusammen,</p>


                        <!--bindings={
  "ng-reflect-ng-if": "false"
}-->

and not the content of the container, and give me a error, any idea if there is away to this.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Miguel Frias
  • 2,544
  • 8
  • 32
  • 53

1 Answers1

3

I would use a directive that you can attach to a container element. The directive applies the appropriate styles so that everything outside the element is not printed and everything inside is.

Directive

@Directive({
  selector: '[print-section]',
})
export class PrintSectionDirective implements AfterViewInit, OnDestroy {
  @HostBinding('class.print-section') private printSection = true;
  private style: HTMLStyleElement;

  public ngAfterViewInit() {
    this.style = document.createElement('style');
    this.style.type = 'text/css';
    this.style.innerText = `
    @media print {
      body * {
        visibility: hidden;
      }
      .print-section, .print-section * {
        visibility: visible;
      }
      .print-section {
        width: 100%;
      }
    }`;

    document.head.appendChild(this.style);
  }

  public ngOnDestroy() {
    document.head.removeChild(this.style);
  }
}

Usage

template

<div print-section>Print only this content</div>
<button (click)="printThePage()">Print Content</button>

component

public printThePage() {
  window.print();
}

The advantages of this method is that the page will still be able to be printed with the default behavior when the directive is not used and when it is attached then only that section of the page will be printed and it will fit the width of the page.

Teddy Sterne
  • 13,774
  • 2
  • 46
  • 51