Printing content from a web page using window.print() function in a form using javascript and angular

Within my HTML code lies a form, complete with a variety of fields:

        <div class="card-body" id="print">
          <form [formGroup]="form">
                  <div class="text-muted" *ngFor="let field of category.fields">
                    <h5>
                      {{ field.name }}
                    </h5>
                    <ng-container *ngIf="field.type === 'text' || field.type === 'number'" >
                      <input
                        formControlName="{{ field.key }}"
                        type="{{ field.type }}"
                        class="form-control"
                        placeholder="{{ field.name }}"
                      />
                    </ng-container>

                    <ng-container *ngIf="field.type === 'textarea'">
                      <textarea
                        formControlName="{{ field.key }}"
                        class="form-control"
                        placeholder="Comments"
                      ></textarea>
                    </ng-container>

                    <ng-container *ngIf="field.type === 'date'">
                      <div
                        class="input-group"
                      >
                        <input
                          formControlName="{{ field.key }}"
                          ngbDatepicker
                          #dateField="ngbDatepicker"
                          type="text"
                          class="form-control"
                          placeholder="DD/MM/YYYY"
                        />
                        <div class="input-group-append">
                          <div
                            class="input-group-text"
                            (click)="dateField.toggle()"
                          >
                            <i
                              class="fa fa-calendar"
                              style="cursor: pointer;"
                            ></i>
                          </div>
                        </div>
                      </div>
                    </ng-container>

                    <ng-container *ngIf="field.type === 'dropdown'">
                      <select
                        class="custom-select"
                        formControlName="{{ field.key }}"
                      >
                        <option [ngValue]="null">
                          Select {{ field.name }}
                        </option>
                        <option
                          *ngFor="let option of field.options"
                          [ngValue]="option.value"
                        >
                          {{ option.label }}
                        </option>
                      </select>
                      <br />
                    </ng-container>

                    <ng-container
                      *ngIf="field.type === 'checkbox_multi_choice'"
                    >
                      <div
                        class="form-check mb-1"
                        *ngFor="let option of field.options"
                      >
                        <p-checkbox
                          class="mr-1"
                          [formControl]="form.controls[field.key]"
                          [value]="option.value"
                        ></p-checkbox>
                        <label class="form-check-label"
                          >{{ option.label }}</label
                        >
                      </div>
                    </ng-container>

                    <ng-container *ngIf="field.type === 'radio'">
                      <div
                        class="form-check"
                        *ngFor="let option of field.options"
                      >
                        <input
                          type="radio"
                          [value]="option.value"
                          formControlName="{{ field.key }}"
                          class="form-check-input"
                        />
                        <label class="form-check-label"
                          >{{ option.label }}</label
                        >
                      </div>
                    </ng-container>
                  </div>
                </ng-container>
              </ng-container>
            </div>
          </form>
        </div>

When attempting to print this form, I use the following function:

  download() {
    var printContents = document.getElementById("print").innerHTML;
    document.body.innerHTML = printContents;
    window.print();
    location.reload();
  }

The function works, but only the values of the 'checkbox_multi_choice' fields are displayed in the print. How can I ensure all input field values are shown when printing?

UPDATE

Credit to @majusebetter, I have managed to display the text box values, but the radio button contents are still not showing. The updated code is provided below. Can someone assist in enabling the radio buttons to display correctly?

  download() {
    let element: any = document.getElementById("print");
    const iframe = document.body.appendChild(document.createElement("iframe"));

    iframe.style.display = "none";

    const idoc = iframe.contentDocument;
    idoc.head.innerHTML = document.head.innerHTML;
    idoc.body.innerHTML = element.innerHTML;

    const inputs = element.querySelectorAll("input");
    const printInputs = idoc.body.querySelectorAll("input");

    for (let i = 0; i < inputs.length; i++) {
      printInputs[i].value = inputs[i].value;
    }

    const selects = element.querySelectorAll("select");
    const printSelects = idoc.body.querySelectorAll("select");

    for (let i = 0; i < selects.length; i++) {
      printSelects[i].value = selects[i].value;
    }

    window.setTimeout(() => {
      iframe.contentWindow.print();
      document.body.removeChild(iframe);
    }, 1000);
  }

Answer ā„–1

To create a printable version of HTML content, one approach is to utilize an IFRAME element. This involves copying the HTML content and styles to the IFRAME, as well as transferring input and select values from the original elements to their counterparts within the IFRAME:

convertToPrintable(element: HTMLElement): void {
    const iframe = document.body.appendChild(
        document.createElement('iframe'));

    iframe.style.display = 'none';

    const iframeDoc = iframe.contentDocument;
    iframeDoc.head.innerHTML = document.head.innerHTML;
    iframeDoc.body.innerHTML = element.innerHTML;

    const inputs = element.querySelectorAll('input');
    const printInputs = iframeDoc.body.querySelectorAll('input');

    for (let i = 0; i < inputs.length; i++) {
        printInputs[i].value = inputs[i].value;
        printInputs[i].checked = inputs[i].checked;
    }

    const selects = element.querySelectorAll('select');
    const printSelects = iframeDoc.body.querySelectorAll('select');

    for (let i = 0; i < selects.length; i++) {
        printSelects[i].value = selects[i].value;
    }

    const radios = element.querySelectorAll('input[type="radio"]');
    const printRadios = iframeDoc.body.querySelectorAll('input[type="radio"]');

    for (let i = 0; i < radios.length; i++) {
        printRadios[i].checked = radios[i].checked;
    }

    window.setTimeout(() => {
        iframe.contentWindow.print();
        document.body.removeChild(iframe);
    }, 1000);
}

UPDATE Included code handling radio button values:

printRadios[i].checked = radios[i].checked;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to adjust the footer width to match the sidebar using Bootstrap 5?

Currently working on a Bootstrap 5 template for my website, but being new to it makes it a bit challenging. Specifically struggling with aligning the footer to fit the full width of the sidebar. <!DOCTYPE html> <html lang="en"> <head&g ...

Working with JSON in the Angular frontend

Looking for assistance to display my JSON data in an Angular frontend in a tree-like structure or an extension. Here is my backend JSON, it consists of a Buildings array grouped by campuses for relational MongoDB databases. [ { "_id": "campus4", "bui ...

Is it possible to adjust the range of a range slider based on the selection of a radio button or other input method?

I have a query and Iā€™m hopeful you can assist: function UpdateTemperature() { var selectedGrade = $( "input[name='radios']:checked" ).val(); $( ".c_f" ).text(selectedGrade); var value1 = $("#tempMin").val(); var value2 = $("#tempM ...

Angular2 array sorting function is not functioning properly on mobile browsers

I'm currently working with a code snippet that looks like this: const words = ['apple', 'banana', 'zoom'] words.sort((first, second) => { const a = first; const b = second; return a == b ? 0 : a < b || a == ...

Tips for transferring a list via ajax to a controller

Having a controller as follows.. public ActionResult Report(List<string> invoiceIds) and utilizing an ajax call like this... function generateAccountsPayableReports() { var ms = $("#msInvoicesAPV").data("kendoMultiSelect"); var invoices = ...

Create a parent dropdown class that contains two separate bootstrap dropdowns nested within it

I am encountering an issue with my dropdown menus. I have 2 dropdown menu items under the same parent dropdown class. However, when I click on dropdown action 1, it displays the body of dropdown menu 2 items instead. <!DOCTYPE html> <html> < ...

Is it necessary to incorporate a Controller along with PostgreSql?

Currently, I'm in the process of working on a project and aiming for well-organized coding practices. However, I find myself puzzled by the concept of controllers. According to my research, it appears that controllers are primarily used when dealing w ...

What is the best way to apply fading effects to three divs containing additional divs?

Looking at this HTML and CSS code: HTML <DIV class="newsPic"></DIV> <DIV class="newsPicTwo"></DIV> <DIV class="newsPicThree"></DIV> CSS .newsPic { width: 500px; height: 200px; } .newsPicTwo { width: 500px; height: 2 ...

Restrict access to table records by specifying an array of row identifiers

Hi everyone, I've encountered a small issue. Just to provide some background, I have a table with checkboxes. Each row in the table has an associated ID, and when selected, I receive an array like this: const mySelectedRoles = [1997, 1998, 1999] Once ...

Neither req.body nor req.file contain any data

Hey everyone, I'm new to coding and currently working on creating a basic markdown blog. However, I'm facing an issue where req.body doesn't contain my markdown field and req.file is undefined when trying to upload an article. I'm unsur ...

What are some ways to enable text highlighting when it is disabled?

I've encountered an issue with text highlighting in my asp.net web application when using the latest versions of FireFox and Google Chrome. Strangely, pressing CTRL+A also does not work for all input fields. I haven't had the opportunity to test ...

Is it possible to vertically displace an element within a CSS Grid cell?

Here is the code snippet: .grid-container { display: grid; grid-template-columns: auto auto auto; background-color: #2196F3; padding: 10px; } .grid-item { background-color: rgba(255, 255, 255, 0.8); border: 1px solid rgba(0, 0, 0, 0.8); ...

The styles within a media query are not being successfully implemented

update: issue resolved. I discovered that there was a lingering media query in the css file that was meant to be removed. Also, I corrected some errors in the code. Thank you all for your help ā€“ it's now working perfectly. I have a set of html and ...

Is it possible to alter the state of one page by clicking a link on another page?

Is it possible to update the state of a different page when a link is clicked and the user navigates to that page? For example: Homepage <Link href="/about"> <button>Click here for the About page</button> </Link> If a ...

Remove old photo when uploading new one in Django

I'm currently working on a user profile feature that allows users to upload profile pictures. The uploading process is functioning correctly, but I'm encountering an issue where the old photo is not replaced when a new one is uploaded. I'm u ...

Developers specializing in Google Maps navigate to a particular destination

I have been working on an app that provides users with the best options for places to visit, utilizing Google Maps technology. Here is what I have accomplished so far: Show the user their current location Show the user possible destinations (with marker ...

What is the best way to shrink or enlarge individual sections of the accordion?

Exploring AngularJs Accordions I'm struggling to understand how to control accordions in AngularJS. I have a step-by-step module set up as an accordion and I want to collapse one part while expanding another based on completion. Here is the accordion ...

A Multilingual Application developed using either AngularJS or the Ionic Framework

Having recently delved into both AngularJS and the Ionic Framework, my background is primarily in Microsoft technologies. I am currently working on developing an app that supports three languages: English, Arabic, and French. Drawing from my experience wi ...

The `staticAlert` property in the constructor.ts file does not have an initializer and is not explicitly assigned

import { Component, OnInit, ViewChild } from '@angular/core'; import {Subject} from 'rxjs'; import {debounceTime} from 'rxjs/operators'; import {NgbAlert} from '@ng-bootstrap/ng-bootstrap'; @Component({ selecto ...

Any suggestions on how to address vulnerabilities in npm when upgrading the main dependency version is not an option?

I recently ran the npm audit --production command and found a high-risk vulnerability related to the snowflake-sdk dependency. After checking the snowflake github page, I noticed that the package.json file includes "requestretry": "^6.0.0&qu ...