I have two section in a HTML page. One is for getting the values and another is the view for PDF.
Since both in same page I want the PDF view to be hidden all the time. Only if someone hits Generate PDF
, it should come as PDF.
<div class="col-12">
<input [(ngModel)]="fName" name="fname" placeholder="First Name">
<input [(ngModel)]="LName" name="lname" placeholder="Last Name">
</div>
<div #PDF>
<p>My Name is</p>
<p>{{fName}} {{lName}}<p>
</div>
<button class-"btn btn-primary" type="submit" (click)="pdfMethod">PDF</button>
TS
import * as jsPDF from 'jspdf'
@ViewChild('PDF') PDF: ElementRef;
pdfMethod(){
var pdf = new jsPDF('p', 'pt', 'letter');
pdf.addHTML(this.PDF.nativeElement, () => {
pdf.save(`sum.pdf`);
});
}
I want input fields to be visible first and the #PDF in pdf format if they click the button. I have used *ngIf
but it is showing native element not defined
This is because you need to wait for the next change detection cycle so that angular has time to create the PDF div and populate its content. Try using ChangeDetecorRef to manually trigger change detection for the component before doing PDF rendering
component.html
<div #PDF *ngIf="showPDF">
<p>My Name is</p>
<p>{{fName}} {{lName}}<p>
</div>
<button class="btn btn-primary" type="submit" (click)="pdfMethod()">PDF</button>
component.ts
import { Component,ViewChild,ElementRef, ChangeDetectorRef } from '@angular/core';
constructor(private cdr: ChangeDetectorRef){}
showPDF = false;
@ViewChild('PDF') PDF: ElementRef;
//@ViewChild('PDF', {static: false) PDF: ElementRef;//for angular 9
pdfMethod()
{
this.showPDF = true;
this.cdr.detectChanges();
var pdf = new jsPDF('p', 'pt', 'letter');
pdf.addHTML(this.PDF.nativeElement, () => {
pdf.save(`sum.pdf`);
});
}