What is the best way to reproduce the appearance of a div from a web page when printing using typescript in Angular 4?

Whenever I try to print a div from the webpage, the elements of the div end up on the side of the print tab instead. How can I fix this issue?

Below is my current print function:

print(): void {
let printContents, popupWin;
printContents = document.getElementById('print-section').innerHTML;
popupWin = window.open('', '_blank');
popupWin.document.open();
popupWin.document.write(`
  <html>
    <head>
      <title></title>
      <style>


      </style>
    </head>
<body onload="window.print();window.close()">${printContents}</body>
  </html>`
);
popupWin.document.close();

}

I've heard that using CSS might solve this problem. Where should I add the CSS code? I've tried including it in the style tag but it doesn't seem to work.

Answer №1

To implement this functionality using Angular InnerHTML directive-binding, consider the code snippet below:

printDocument(): void {
let printContent, popupWindow;
printContent = document.getElementById('print-section').innerHTML;
popupWindow = window.open('', '_blank');
popupWindow.document.open();
popupWindow.document.write(`
  <html>
    <head>
      <title></title>
      <style>


      </style>
    </head>
<body onload="window.print();window.close()">
    <div [innerHTML]="printContent"></div>
</body>
  </html>`
);
popupWindow.document.close();

Answer №2

Using CSS and media queries can help solve this issue effectively. Each Angular component should have its own .css file where you can include the necessary styles.

Here is an example of CSS code:

@media screen and (max-width: 600px) {
 /* Add your responsive styles here */
 #sidebar { display: none; }
}

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

I am unable to access the object property in Typescript

Here is an object definition: const parsers = { belgianMobile: (input: string) => input.replace(/^(0032|0)(\d{3})(\d{2})(\d{2})(\d{2})/, '$1$2 $3 $4 $5').replace('0032', '+ 32 '), }; Now, I want ...

provide an element reference as an argument to a directive

I am trying to figure out how to pass an element reference to a directive. I know that I can get the reference of the element where the directive is applied using private _elemRef: ElementRef but my goal is to pass the reference of another element to the ...

Tips for enhancing a TypeScript interface for a React component in (Material-UI) by utilizing styled-components

I've been struggling to find a solution for this overload issue with no luck so far. My stack includes Typescript, Styled-components, and Material-UI. I am utilizing styled(MUIButton) to extend the default Button from MUI. While my props are being pas ...

Is it necessary to use ReplaySubject after using location.back() in Angular 6 to avoid requesting data multiple times?

I'm currently utilizing a BehaviorSubject in my service to retrieve data from the BackEnd, which I subscribe to in my mainComponent using the async pipe. However, whenever I navigate to another subComponent and then return to my mainComponent by clic ...

Tips on invoking Bootstrap's collapse function without using JQuery

We are facing a challenge with our TypeScript files as we have no access to jQuery from them. Our goal is to trigger Bootstrap's collapse method... $(object).collapse(method) but without relying on jQuery. Intended Outcome //Replicates the functio ...

Currently, I am collaborating on an e-commerce endeavor utilizing TypeScript and sanity.io, encountering an issue along the way

Encountering an Uncaught TypeError message: Cannot read properties of undefined (reading '_ref'). While attempting to utilize code for displaying API content on a webpage, what might be causing this issue and how can it be resolved to successful ...

Disable Styling and Override Readonly CSS restrictions

What is the correct approach for customizing material design styling when input fields are disabled? Out of the Box https://i.sstatic.net/CvcAV.png Explore Angular Material Input Examples I managed to achieve my objective using the following CSS, but I ...

Sending Svelte data to Javascript with an onclick event

In my Svelte store, I have an ASCII-Logo that I want to integrate into a button spanning two symbols ("-."). However, I do not want to split the ASCII into separate parts and just insert the button between them on my +page.svelte. Currently, I h ...

Compiler raises concerns about potential undefined values in nested objects

In my code snippet, I am experiencing an issue with TypeScript when I try to access an object property after checking for its existence. The sample code can be found here (when strictNullChecks is enabled). 1. let boolVar: number | undefined; 2. 3. if ...

App that uses Angular 2 for real-time data refreshing

As a newcomer to Angular and Nodejs, I am venturing into the development of a MEAN stack cryptocurrency exchange application. My approach involves setting up a nodejs backend to retrieve the current exchange rate from an API and presenting it in the HTML. ...

Is it possible to utilize Angular translate to support multiple languages for individual components or modules?

Utilizing ngx-translate to switch the language of my application has proven to be quite challenging. My application consists of different languages specifically for testing purposes and is divided into separate modules with lazy loading functionality. As ...

Is it considered poor practice to specify the type explicitly when it can be easily inferred by Tslint?

When using VSCode, the linter tslint may raise an issue when the following code is added with a specific type: serverId: number = 10; This will trigger the following message: [tslint] Type number trivially inferred from a number literal, remove type ...

Merge arrays values with Object.assign function

I have a function that returns an object where the keys are strings and the values are arrays of strings: {"myType1": ["123"]} What I want to do is merge all the results it's returning. For example, if I have: {"myType1": ["123"]} {"myType2": ["45 ...

What steps can be taken to address the build problem with Angular version 13?

Encountering a problem while working with Angular 13: https://i.sstatic.net/CbAUhh6r.png Attempting to build using ng build --configuration=test, however facing errors as mentioned above. Interestingly, if I remove the reference to bootstrap.min.css in t ...

Issue encountered with ASP.Net Core on AWS Serverless: The middleware for the SPA default page was unable to locate and return the default page '/index.html'

Everything works flawlessly with my ASP.Net Core 6.0 application with Angular on Visual Studio, but once deployed to AWS Serverless and accessing '/', an error occurs. The default SPA page middleware cannot serve the default page '/index.h ...

Leverage TypeScript's enum feature by incorporating methods within each enum

In my TypeScript file, I have defined various events and interfaces: export type TSumanToString = () => string; export interface ISumanEvent { explanation: string, toString: TSumanToString } export interface ISumanEvents{ [key: string]: ...

Encountered an issue while attempting to load the TSLint library for the document within Visual Studio Code

After setting up the latest versions of Visual Studio Code, Node.js, and Typescript on my Windows 10 system, I encountered an issue when trying to utilize TSLint in the terminal. A message appeared stating: Failed to load the TSLint library for the documen ...

Removing punctuation from time duration using Moment.js duration format can be achieved through a simple process

Currently, I am utilizing the moment duration format library to calculate the total duration of time. It is working as expected, but a slight issue arises when the time duration exceeds 4 digits - it automatically adds a comma in the hours section (similar ...

Guide to developing a dynamic method while utilizing IntelliSense assistance

When utilizing itemsApi in React reduxTool kit, dynamic functions like use..., mutate... are generated. These dynamically created methods possess complete intelligence as well. For instance, if you have createApi({... getItems: builder.query<any, st ...

There was an issue converting the value {null} to the data type 'System.Int32', resulting in a 400 error

Attempting to make a POST request with some missing data is causing errors in my angular form. Here is the payload I am using: DeviceDetail{ deviceId:'332', sideId: null, deviceName:'test' } Unfortunately, I encountered a 400 bad re ...