There seems to be an issue with a potentially null object in an Angular project while trying to view a PDF file

IDENTIFY THE ERROR:

printContents = document.getElementById('print').innerHTML.toString();

ON LINE 4:

print(): void {
    let printContents!: string;
    let popupWin!: any;
    printContents = document.getElementById('print').innerHTML.toString();
    printContents = ((printContents as string) + '').replace('col-sm', 'col-xs');
    popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
    popupWin.document.open();
    popupWin.document.write(`<html lang="fa"><body onload="window.print();">${printContents}</body></html>`);
    popupWin.document.close();}

Answer №1

If the element does not exist, <code>getElementById
can return undefined.

To ensure success, use

document.getElementById('print')!.innerHTML.toString();
.

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

"Optimizing Image Display in Web Browsers

Currently, I am using JavaScript to dynamically size a transparent .gif on my website. The original image size is approximately 200x200 pixels, but it's usually resized to be between 600x600 and 800x800. When viewing the resized image in IE8 and FF3, ...

Tips for parsing through extensive JSON documents containing diverse data types

In the process of developing an npm package that reads json files and validates their content against predefined json-schemas, I encountered issues when handling larger file sizes (50MB+). When attempting to parse these large files, I faced memory allocati ...

Script tag in NextJS

After numerous attempts, I am still struggling with a specific task on this website. The challenge is to insert a script tag that will embed a contact form and newsletter sign-up form, among others, on specific pages of the site. For instance, the contact ...

Use setTimeout and setInterval with the initial input without parentheses or double quotation marks

<!DOCTYPE HTML> <html> <head> <script type="text/javascript"> var count=0; function increaseCount(){ document.getElementById('txt').value=count; count++; setTimeout(increaseCount(),1000); } </script> </head&g ...

What is the best practice for adding one string to the end of another?

So, is this the best way to concatenate strings in JavaScript? var str = 'Hello'; str += ' World'; While most languages allow for this method of string concatenation, some consider it less efficient. Many programming languages offer a ...

Guide to accessing contact list on Ionic framework

I'm new to using Ionic and I'm trying to access the contact list in my app to display contacts only. Can someone please guide me on how to achieve this? I watched a tutorial on YouTube but the code provided doesn't seem to work. I've ad ...

Combining Multiple 3D JSON Objects in JavaScript [or jQuery]

Looking to combine multiple JSON objects into one? I have a code snippet that you can use! Here is the code: http://jsfiddle.net/5Uz27/ The issue with this code is that it only merges objects on the first level, causing deeper levels to be overwritten. T ...

JQuery: Creating a visually striking screen flash

How can I make the window or page flash/blink using JQuery or plain JavaScript? I also want to get the tab to flash at the same time. Currently, the code I have is: var flash = true; var alert = setInterval(function(){ if (flash) //doFlash ...

How to fix the TS4090 error regarding conflicting definitions for a node in Visual Studio 2017

My TypeScript project is building and running, but I'm encountering a multitude of build errors all originating from one issue: TS4090: (TS) Conflicting definitions for 'node' found at 'C:/[projectpath]/node_modules/@types/node/index ...

"Enhancing the speed of the JavaScript translate function when triggered by a scroll

I am facing an issue with setting transform: translateY(); based on the scroll event value. Essentially, when the scroll event is triggered, #moveme disappears. For a live demonstration, please check out this fiddle: https://jsfiddle.net/bo6e0wet/1/ Bel ...

During the installation of a package, npm encountered a require stack error with the code MODULE_NOT_FOUND

Whenever I attempt to install something using the npm install command, it throws an error saying "require stack" and "code MODULE_NOT_FOUND" C:\Users\dell>npm audit fix node:internal/modules/cjs/loader:1075 const err = new Error(message); ...

Executing numerous queries in mongoDB

I need to query multiple collections in MongoDB. Here is an example of the data structure: Collection stops { { stop_id : 1, stop_name: 'a'}, { stop_id : 2, stop_name: 'b'}, ... Collection stop_time { { stop_id : 1, trip_i ...

Having trouble accessing the 'add' property of Rxjs Subscription

I have been working on optimizing my code and I encountered an issue with unsubscribing from multiple subscriptions in ngOnDestroy. Specifically, when trying to invoke the add() method to include additional child subscriptions, I keep getting an error me ...

Improving my solution with PrimeNG in Angular2 - fixing the undefined tag error

After working with Angular for just three days, I successfully set up a login page dashboard using a web API solution. Everything was working great until I encountered an issue when trying to load the PrimeNG DataTableModule into my components. After searc ...

Service Worker Tips: Caching the initial page with dynamic content

I have a single-page application with a dynamic URL generated using a token, for example: example.com/XV252GTH, which includes various assets such as CSS and favicon. This is how I implement the Service Worker registration: navigator.serviceWorker.regist ...

In Vue Js, the function createUserWithEmailAndPassword does not exist within _firebase_config__WEBPACK_IMPORTED_MODULE_3__.default

My createUserWithEmailAndPassword function seems to be malfunctioning. Here is the code snippet I am using - config.js import firebase from 'firebase/app' import 'firebase/firestore' import 'firebase/auth' const firebaseCon ...

How can I restrict website access to only specific IP addresses?

I am looking to restrict access to certain IP addresses on a website, but the issue is that dynamic IPs keep changing based on the source of internet connection. Is there a method to determine the static IP of the computer rather than relying on the dyna ...

Tips for combining text and variable outcomes in printing

I created a calculator that is functioning correctly and displaying results. However, I would like to include a text along with the results. For example: You spent "variable result" dollars in the transaction. Currently, the results are shown only after ...

An instructional guide on seamlessly incorporating a TypeScript variable into an HTML element submission method

A problem arises in my Angular 8/Django 3 app as I attempt to incorporate a server-side variable called client_secret into the stripe.confirmCardPayment() method. The error message that keeps popping up is Property 'client_secret' does not exist ...

Exploring the relationship between React component inheritance and asynchronous requests

I'm struggling to comprehend why this isn't functioning var link = window.location.href; var array = link.split('/'); var sub = array[array.length-1]; console.log(sub); var name; var posts; var upvotes; var ProfileFiller = React.creat ...