Introduction
Mostly on the internet, you can find how to open PDF via window.open(“”) Javascript way.
Read more
So what is here?
Well, opening PDF in a separate window is available but is not in our custom control, especially in Angular.
So here we will open this PDF inside our custom dialog (in our control) and can do event firing on the closing of POP up for further business requirements.
Prerequisite(not mandatory)
I am using a ready-made dialog box from prime-ng <p-dialog> control.
Read more - http://primefaces.org/primeng/dialog
But that is not required you can use any material bootstrap or custom div even. This is just to showcase because behind the scene the logic is the same.
Read more - https://material.angular.io/components/dialog/overview
Opening PDF In Angular
Opening PDF inside a dialog can be done in a few ways. The Idea/concept behind this is we need to get elementID from DOM and attach our PDF to its inner body. Using below ways
- Using <a href =”url”>.
- Using the same anchor tag by dynamic code and click it.
- Using <iframe/> and appending to DOM body.
- Using .getElementById(“”) and binding to its innerHTML.
Problem
Many times you use “ElementRef, Renderer2” packages which we generally use but you get errors like this:
a. Use @Viewchild()
Read more - https://www.c-sharpcorner.com/article/simplifying-viewchild-and-viewchildren-in-angular-5/
Alternate Solution
b. Use @inject(document)
Read more - https://www.c-sharpcorner.com/blogs/quick-tip-injecting-document-in-angular-component
Steps
Step 1. Inject the document in the constructor and import it from the library like this.
@Inject(DOCUMENT) private document: Document
Import Library
import { DOCUMENT } from '@angular/common';
Step 2. Use it like this, here I am creating DOM <Frame> element and binding it to Element ID where I want it to display behind the HTML side
Ts Code
Html code
Step 3. It should open like this when you open it inside HTML similar can be done in dialog or popup container:
In Main Body
In POP up
Attachment
Full project will not help as Angular has many packages, so I am giving this simple JavaScript version POC used for angular application. Kindly refer to angular code screenshots (typescript version for reference)
Client-Side coding with a new framework is always fun, Let me know if you have any queries.
Happy coding and Happy New Year - 2023.