Switch back emulation when moving away from page - using angular javascript

I have a unique scenario in my component.ts file on a specific page where I need to incorporate custom CSS for printing purposes:

@Component({
  selector: "dashboard",
  templateUrl: "./dashboard.component.html",
  styleUrls: ["./dashboard.component.scss"],
  encapsulation: ViewEncapsulation.None
})

However, I am looking for a way to revert back to the default encapsulation when navigating away from this page. Is there a solution for this?

Alternatively, is it possible to apply encapsulation only when the print button is clicked, and then automatically switch back to normal afterwards?

If I navigate away and refresh the page, the encapsulation returns to its default state across all pages, but I prefer not to rely on refreshing.

EDIT

The reason behind adding the encapsulation was to allow for landscape printing by using the following code within the scss file:

@media print {
    @page {
      size: landscape 
    }
    .no-print,
    .no-print * {
      display: none !important;
    }
    body {
      -webkit-print-color-adjust: exact;
    }
    canvas {
      max-width: 100%;
      height: auto;
    }
    .printClass {
      display: inline-block;
    }
  }

Without this adjustment, the global scss styling would cause the printed output to be portrait every time.

Answer №1

Affirmative. In this instance, we are utilizing the ngx-print library, which is accessible on GitHub. Although not mandatory, it presents an effective and straightforward approach.

npm install ngx-print

Utilization

 <!--
   1)- Insert an ID here
 -->
<div id="print-section"> 
  <!--Your desired HTML content for printing-->
</div>

 <!--
   2)- Include the directive name in your button (ngxPrint),
   3)- Assign your ID to printSectionId
 -->
<button printSectionId="print-section" ngxPrint>print</button> 

You can customize styles with CSS. Below is a demonstration:

  1. When I avoid applying CSS using [useExistingCss]="true", the Layout dropdown option (portrait or landscape) appears during the print process.
  2. Despite having a @media print{@page {size: landscape}} rule in my CSS, it seems to be disregarded by ngx-print.
  3. By using {size: landscape !important}, the output will be in landscape orientation.
  4. If {size: auto !important} is used, the Layout option will be displayed.

This section reflects the essence of it:

public print(): void {
    let printContents, popupWin, styles = '', links = '';
    const baseTag = this.getElementTag('base');

    if(this.useExistingCss) {
      styles = this.getElementTag('style');
      links = this.getElementTag('link');
    }

    printContents = this.getHtmlContents();
    popupWin = window.open("", "_blank", "top=0,left=0,height=auto,width=auto");
    popupWin.document.open();
    popupWin.document.write(`
      <html>
        <head>
          <title>${this.printTitle ? this.printTitle : ""}</title>
          ${baseTag}
          ${this.returnStyleValues()}
          ${this.returnStyleSheetLinkTags()}
          ${styles}
          ${links}
        </head>
        <body>
          ${printContents}
          <script defer>
            function triggerPrint(event) {
              window.removeEventListener('load', triggerPrint, false);
              ${this.previewOnly ? '' : `setTimeout(function() {
                closeWindow(window.print());
              }, ${this.printDelay});`}
            }
            function closeWindow(){
                window.close();
            }
            window.addEventListener('load', triggerPrint, false);
          </script>
        </body>
      </html>`);
    popupWin.document.close();

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

Extract a value from an array that is not located at the array's tail using Javascript

In my array pvalue, each number is unique. It contains: 1 2 3 15 20 12 14 18 7 8 (total of 10 numbers). My goal is to remove the number "15" from the array, resulting in pvalue being: 1 2 3 20 12 14 18 7 8 (now with 9 numbers). How can I achieve this with ...

Unable to trigger click event on SVG path element

Hey there, I'm currently working on a project and I'm having some trouble with the click event for my SVG paths. $path.map(function(){ $(this).mouseenter(function(){ $count = $path.attr('data-like'); $('#coun ...

I am experiencing some issues with my AngularJS JavaScript code. The root scope is updating correctly, but the other two scopes are not working as expected. Can

My attempt at writing AngularJS JavaScript code seems to be malfunctioning. While the root scope updates properly, the other two scopes FirstCtrl and SecondCtrl do not update as expected when the root scope is updated. I would like all three scopes to upd ...

Error: The hyperlink in the response from the Ajax request is not functioning as expected

I've exhausted all the suggestions for fixing this issue, but nothing has worked so far. Currently, my setup involves making an AJAX call to a PHP page called livesearch.php from the index page in order to retrieve live search results. <html> ...

How about creating a fresh variable in Assemble or merging two comparison helpers together?

Is it possible to create a new variable within a partial in Assemble (assemble.io) or combine two comparison helpers? For example: {#is somevar "yes" || anothervar "no"} In my partial, I have HTML that should only display if one of two different variable ...

Maintaining an element's vertical position in relation to the screen with jQuery

I'm very close to achieving what I want, but my goal is a bit unconventional. My setup includes several panels divided into 2 columns, with each panel capable of triggering an expand/compress toggle. My challenge is maintaining the vertical position ...

Exploring AngularJS and Jasmine: Testing a controller function that interacts with a service via $http

I encountered an issue while testing a controller that relies on a service. The problem arises because the service is currently set to null in order to focus solely on testing the controller. The current test setup is failing due to the BoardService being ...

React Native - Issue with array value not reflecting in Text component

import React, {useState} from 'react'; import { FlatList, Text, View} from 'react-native'; import {styles, styleBox} from './components/styles'; import Slider from '@react-native-community/slider'; export default fu ...

Stop the form from refreshing upon submission using an Ajax call in AngularJS

Currently, I am in the process of developing a search form that requires two inputs: Job title and Location. These keywords are used to gather data from various websites. However, upon submitting the form, the page refreshes itself. To prevent this, I have ...

What is the best way to isolate the elements from the specified dictionary that contain valid data?

I need to extract only the data for Flipkart from this array and create a new array containing just that information. json = [ { "amazon": [] }, { "flipkart": { "product_store": "Flipkart", ...

Having trouble with your website not adjusting properly when resizing the browser or viewing it on a mobile phone

My website is not adapting properly to different screen sizes, even after I have added the META tags below. Any advice would be appreciated. Thank you. HTML <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8> ...

Supporting multiple types for matching object structures is a feature in Jest

I'm currently working on a test using jest to verify if an object key is either a string or a number. It seems like a basic task, but surprisingly there isn't much guidance in the documentation. Test Example: test('Checking asset structure ...

Issue with window.location.href and unexpected behavior in Firefox 7

I can't seem to figure out the issue I'm encountering on FF7 My ajax calls are returning a json object (jquery). if(data.result=='ok') { var url = baseURL + "azioni/makeForm/" + data.actcode + "/DIA/" + data.az_id; console.log ...

Can you explain the distinction between escapeXml and escapeHtml functions?

When it comes to escaping characters in JSP pages, I am wondering which is the better option - using escapeXml or escapeHtml? ...

Bug with IE lookahead in Regular Expressions

Currently, I am struggling to define the regular expression needed for proper validation in my ASP.NET validator. Although it works fine in Firefox, the sample string is not validating correctly in IE using the following expression: 12{2}12{0-9}1{12,13} ...

Discovering the process of reaching service members through an HTML View

Currently, I am in the process of learning Angular 2 and find myself unsure about the most efficient way to update the view. For instance, let's say I have two components: User and Main. The User component retrieves a list of users from the UserServ ...

How to retrieve the selected values of specific option tags using jQuery?

I have a situation where I need to select an option from a dropdown menu. Here is the code for the dropdown: <select id="customUser_id" name="customUser_id"> <option value="2" label="Friends Of Friends">Friends Of Friends</option> &l ...

What are the best circumstances to utilize jQuery-UI autocomplete feature?

Looking for assistance in creating an input field that auto-populates user-entered values with database entries. Only values that exist in the database should be accepted. Could someone explain the advantages of using jQuery-ui autocomplete for this task ...

What is the process of running PHP in a .ctp file within the CakePHP framework?

I have recently started working with CakePHP and I have a question about how PHP code is executed in a file with the .ctp extension. Can you explain how PHP is processed within a .ctp file in CakePHP? Additionally, I'm also curious about executing PHP ...

Create a bootstrap table with td elements that have no wrap for their content

I am currently developing an application using springboot, thymeleaf, and bootstrap. Here is the snippet of the html code I'm working with: <!doctype html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <h ...