i have an angular 4 app and i have a function to print a content. here is part of my ts file:
print(id) {
// console.log(temp)
this.templateservice.getTemplateById(id).subscribe(template => {
  if (!template.success) {
    this.snackbar.open(template.message, '', {
      duration: 2000,
      extraClasses: ['success-snackbar']
    });
  } else {
    let headContents, innerContents, signContents, popupWin;
    headContents = document.getElementById('head-section').innerHTML;
    innerContents = document.getElementById('inner-section').innerHTML;
    signContents = document.getElementById('sign-section').innerHTML;
    console.log(headContents);
    popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
    console.log(popupWin)
    popupWin.document.open();
    popupWin.document.write('<html><head><style></style></head><body onload="window.print();window.close()"><p class="head">' + headContents + '</p> <p class="inner">' + innerContents + '</p> <p class="sign">' + signContents + '</p></body></html>');
    popupWin.document.close();
  }
});// end of subscribe
}//end of print
and this is my html file:
<md-tab>
          <ng-template md-tab-label>Outgoing Mail</ng-template>
          <md-card-content >
            <div fxLayout="column" fxLayoutAlign="center center" class="mt-1" >
              <div class="template" style="@page  {size: A4};width: 210mm;height: 297mm;border-width: 2px;border-style: solid;border-color: #e6e6e6;padding-top: 23mm;padding-left: 2cm;padding-right: 2.5cm;padding-bottom: 55mm">
                <p class="head" id="head-section" style="line-height: 1cm;padding-left: 152mm;">Mail Number: {{mail_number}} <br> Date: {{created_at| date:'yyyy MMM dd'}}</p>
                <p class="inner" id="inner-section" style="max-height: 873px;line-height: 25px;word-spacing:1px;text-align: justify;padding-right: 20mm;padding-left: 25mm;padding-top: 21mm;padding-bottom: 5mm;white-space: pre-wrap; width: 166mm; word-wrap: break-word;">{{content}}</p>
                <p class="sign" id="sign-section" style="padding-left: 33mm;padding-right: 147mm ;padding-bottom: 70mm;line-height: 1cm;">Sincerely <br> {{sender}}</p>
              </div>
            </div>
          </md-card-content>
        </md-tab>
in this situation i get an error of "cannot read property document of undefined" and if i put the print codes out of the subscribe i can not access the template that is returned by the service! when i write console.log(headContents) i get response. but when i do console.log(popupwin) i get the image bellow! the popupwin is null and i have an error about document

 
     
     
    