2

I am using a reactive form in Angular4. I want to implement print functionality for the same. However, the reactive form values are not shown while printing. How can I achieve this? Posting my code below:

html

<section id="print-section">
    <form [formGroup]="myForm" novalidate>
        <div class="form-child input-wrap">
            <span>Date</span>
            <input type="text" placeholder="Date" class="borderStyle form-control" formControlName="date">
        </div>
        <div class="form-child input-wrap">
            <span>Address</span>
            <input type="text" placeholder="Address" class="borderStyle form-control" formControlName="address">
        </div>
    </form>
</section>

ts

let printContents, popupWin;
    printContents = document.getElementById('print-section').innerHTML;
    popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
    popupWin.document.open();
    popupWin.document.write(`
      <html>
        <head>
          <title>Print tab</title>
          <style>
          </style>
        </head>
    <body onload="window.print();window.close()">${printContents}</body>
      </html>`
    );
    popupWin.document.close();
3
  • why are you not using myForm to print elements value? Add more code specific to your ts Commented May 28, 2018 at 6:57
  • I am trying to print the page. Commented May 28, 2018 at 7:16
  • check update you are missing approch Commented May 28, 2018 at 9:31

1 Answer 1

0

this line

let printContents, popupWin;
    printContents = document.getElementById('print-section').innerHTML;

is incorrect as per coding , that is reason my below answer is not working. if you are using reactive form approach then you should create from in your ts file like as below

export class HeroDetailComponent3 {
  printContents: FormGroup; 

  constructor(private fb: FormBuilder) { // <--- inject FormBuilder
    this.createForm();
  }

  createForm() {
    this.printContents= this.fb.group({
      date: '', 
      address: ''
    });
  }
}

check here for detail : https://angular.io/guide/reactive-forms


if you want form value the do like this

 const json = JSON.stringify( this.printContents.value );
 <body onload="window.print();window.close()">${json }</body>

or try out

I am not sure but you might need to use DomSanitizer, as you are trying to put html elements from angular.

Sign up to request clarification or add additional context in comments.

4 Comments

I got undefined when I did this.
still the same.
@RemyaJ have you used snitizer and can you share your full ts file code
No I already have a form and formcontrol names and all of that. The values are not shown in the print preview

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.