The nativeElement in Angular is not defined

I need help creating a PDF from HTML content within an Angular application.

Check out my main component:

Main Component HTML:

<div class="container-fluid">
    <!-- ... other HTML content ... -->
    <div class="table-responsive">
        <table class="table" #pdfTable>
            <!-- Table content -->
        </table>
    </div>
    <app-pdf-explosion-insumos-proyecto [tableElement]="pdfTable"></app-pdf-explosion-insumos-proyecto>
</div>

Main Component TypeScript:

import { Component, ViewChild, ElementRef, OnInit } from '@angular/core';
// ... other imports ...

@Component({
  selector: 'app-explosion-insumos-concepto',
  templateUrl: './explosion-insumos-concepto.component.html',
  styleUrls: ['./explosion-insumos-concepto.component.css']
})
export class ExplosionInsumosConceptoComponent implements OnInit {
  // ... other properties ...

  @ViewChild('pdfTable', { static: false }) pdfTable: ElementRef;

  // ... constructor and ngOnInit ...
}

Now, let's take a look at the child component:

Child Component HTML:

<button type="button" mat-raised-button mat-min-fab class="btn btn-error btn-round btn-fab float-right" (click)="downloadPDF()">
    <i class="material-icons">picture_as_pdf</i>
</button>

Child Component TypeScript:

import { Component, ElementRef, OnInit, Input, ViewChild } from '@angular/core';
import 'moment/locale/es'; 
import { jsPDF } from 'jspdf';
import html2canvas from 'html2canvas';


@Component({
  selector: 'app-pdf-explosion-insumos-proyecto',
  templateUrl: './pdf-explosion-insumos-proyecto.component.html',
  styleUrls: ['./pdf-explosion-insumos-proyecto.component.css']
})

export class PdfExplosionInsumosProyectoComponent implements OnInit {
  @Input() tableElement: ElementRef;

  constructor() {}

  ngOnInit(): void {}

  downloadPDF() {
    if (this.tableElement) {
      html2canvas(this.tableElement.nativeElement).then(canvas => {
        const imgData = canvas.toDataURL('image/png');
        const doc = new jsPDF({
          orientation: 'landscape',
          unit: 'px',
          format: [canvas.width, canvas.height]
        });
        doc.addImage(imgData, 'PNG', 0, 0, canvas.width, canvas.height);
        doc.save('tabla-explosion-insumos.pdf');
      });
    }
  }
}

I've managed to pass the HTML table data from the parent component to the child successfully. However, I'm facing issues with nativeElement being undefined when performing certain operations.

Answer №1

Modify the input parameter from

@Input() tableElement: ElementRef;
to
@Input() tableElement: HTMLTableElement;

#pdfTable is already the native element that we need.

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

Error message in JS and HTML is totally bizarre

My expertise in JavaScript is very limited, so the terms I use might not be entirely accurate. However, I'll do my best to explain the issue at hand. I'm facing a peculiar problem... I've been attempting to modify someone else's JS scr ...

Converting Enum Values into an Array

Is there a way to extract only the values of an enum and store them in an array? For example, if we have: enum A { dog = 1, cat = 2, ant = 3 } Desired output: ["dog", "cat", "ant"] achieved by: Object.values(A) Unfor ...

Troubleshooting problems encountered in Nest.js due to modifications made within a service.ts file

I'm currently working on a Nest.js project and here is the content of the automobile.service.ts file: import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Car } from './enti ...

Exploring the intricacies of nested arrays

I am searching for a solution to compare arrays within arrays. let small = [[1, 3], [2, 2], [2, 3], [3, 0]]; let large = [[1, 0], [1, 1], [2, 0], [2, 2], [2, 5], [3, 0], [3, 2]]; For instance, I would like to determine how many arrays in small are pres ...

Struggling with making an Ajax and Jquery drop down menu work? Wondering how to use Javascript to retrieve a variable and then utilize it in PHP? Let's troubleshoot

Currently, I am utilizing Ajax/Jquery to present a dropdown menu with data retrieved from my SQL database. The process involves using javascript to obtain a variable that is then utilized in PHP. However, the function doesn't seem to be working as exp ...

Enhancing express functions with additional parameters in Node.JS

I am currently working on optimizing my node application by removing anonymous functions. An example of this is shown below: app.post('/page-edit.json', function (req, res) { db.get(req.body.page_id, function (err, doc) { res.content ...

How do I convert the ImagePicker type to Base64 in Ionic Capacitor?

I am currently developing an app using Ionic (Angular-based) along with Capacitor Plugins, specifically the Camera Plugin. The main feature I am working on involves allowing users to choose up to 5 images from their gallery. To accomplish this, I have impl ...

The silent renewal feature in oidc-client-js is not functioning properly

I have been utilizing the oidc-client-js library to interact with IdentityServer3, and it functions flawlessly. However, I am encountering an issue trying to set up automatic "silent token renew." Every time oidc-client-js attempts to renew the token, I re ...

Ways to update an angular page using the router without resorting to window.location.reload

I have a specific method for resetting values in a component page. The process involves navigating from the "new-edition" page to the "my-editions" component and then returning to the original location at "new-edition". I am currently using this approach ...

Leveraging variables with jQuery within a Django template filter

My goal is to fetch data using Jquery, followed by the application of a Django template filter. The template itself is powered by jinja2. When dealing with a click event, I have the following code: $('#get_name').click(function(event){ var ...

Trouble encountered during AJAX form submission

To ensure the form is submitted via an ajax call and to intercept the result in order to update the page without leaving the index page, follow these steps: I am facing challenges getting the ajax call to work properly. <form action="/cart" me ...

what is the method for passing query string parameters in an XMLHttpRequest to a PHP page

I have a PHP variable named $name=$_POST["name"]; <script> pge = '<?php echo $name ;?>'; var url = "searchCustomerByNameApi2.php" //some code xmlhttp.open("GET", url + "?pge=" + pge, true); xmlhttp ...

steps to incorporate highcharts offline-exporting in typescript

I've tried the configurations below but they are not working as expected. import * as Highcharts from 'highcharts/highstock'; /*import * as HighchartsExporting from 'highcharts/modules/exporting'; HighchartsExporting(Highcharts);* ...

I encountered an issue with displaying a fullcalendar within a pop-up modal

Hey there! I'm facing an issue with setting up a fullcalendar inside a bootstrap modal. When I do so, the calendar appears compressed in the top-left corner and I can't see anything. However, when I resize the screen, it suddenly displays perfect ...

Encountering issues with installing angular/cli due to errors popping up

When attempting to install Angular in my terminal after completing the setup, I encountered the following error message: I have already installed: Node v6.10.3 npm ERR! Darwin 17.7.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g ...

Revamp Your Service Naming and Nickname with Swagger Codegen IO

Is it possible to customize the Swagger IO CodeGen naming conventions for generating Angular API Service Proxies? Check out Swagger Editor here The current convention combines API, Controller Name, Controller Method, and HTTP Action. public apiProductGet ...

Remove an image that has been selected while uploading multiple images using AngularJS

If I want to delete a specific image from multiple uploads by clicking on the image in AngularJS, how can I achieve this? Each uploaded image has an associated textbox. When the delete icon on the image is clicked, both the image and the corresponding text ...

Retrieve the href attribute using jQuery when clicked

Is there a way to capture the href link using jQuery? For instance, consider the following: <li><a href="head.php">Head</a></li> <li><a href="body.php">Body</a></li> <li><a href="settings.php">S ...

Issue with React TypeScript: Only the first state update takes effect, despite multiple updates being made

Check out this sandbox I created here. When you leave any of the form inputs blank, I should be seeing 3 errors but instead, I only get one. Can anyone explain why this is happening? import React, { ChangeEvent, useState } from 'react'; import { ...

Creating trails by following the cursor's movement in KineticJS

Currently, I am working on a drawing application using KineticJS. While I have successfully used it to draw shapes and straight lines by following the method outlined in KineticJS - Drawing Lines with Mouse, I now need to draw a line along the mouse's ...