Troubleshooting problem with thumbnail view feature for PDF files on Angular 2 platform

Recently I started working with angular 2 and encountered an issue while trying to upload a PDF file and display its thumbnail in the UI using ng2-pdf-viewer. The error message I'm facing is:

AppComponent.html:10 ERROR Error: Invalid parameter object: need either .data, .range or .url
    at error (pdf.combined.js:357)
    at Object.getDocument (pdf.combined.js:11832)
    at PdfViewerComponent.webpackJsonp../node_modules/ng2-pdf-viewer/dist/pdf-viewer.component.js.PdfViewerComponent.loadPDF (pdf-viewer.component.js:89)
    at PdfViewerComponent.webpackJsonp../node_modules/ng2-pdf-viewer/dist/pdf-viewer.component.js.PdfViewerComponent.ngOnChanges (pdf-viewer.component.js:78)
    at checkAndUpdateDirectiveInline (core.es5.js:10891)
    ... 

Below are the sections of code involved in my project.

app.component

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import {FormsModule} from '@angular/forms';

import { AppComponent } from './app.component';
import { PdfViewerComponent } from 'ng2-pdf-viewer';

@NgModule({
  declarations: [
    AppComponent,
    PdfViewerComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
platformBrowserDynamic().bootstrapModule(AppModule);

app.component.html

<div class="container">
<div class="form-group col-sm-3">
          <label for="">PDF file</label>
          <input type="file"  (change)="fileChange($event)" accept=".pdf">
        </div>
    <div class="row">
        <div class="col-md-5">
            <div class="thumbnail" style="width: 150px;height: 200px;" (click)="pdfShow=!pdfShow">
                <p>click me to view PDF in Iframe!</p>
                <pdf-viewer [src]="fileData"
                            [page]="page"
                            [original-size]="false"
                            style="display: block;"
                 ></pdf-viewer>
            </div>
            <br>
        </div>
        <div class="col-md-7">
            <div *ngIf="pdfShow">
                <h4>PDF in Iframe</h4>
                <iframe width="500" height="600" [src]="fileData" type="application/pdf"></iframe>
            </div>
        </div>
    </div>
</div>

app.component.ts

import { Component } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  pdfSrc;
  ngOnInit() {
  }

  fileData: File;
  fileChange(event) {
    let fileList: FileList = event.target.files;
    if (fileList.length > 0) {
      this.fileData = fileList[0];
    }
  }
}

If anyone has experience with this issue, your help would be greatly appreciated.

Answer №1

Modifications have been made in app.component.html and app.component.ts. It is now operational.

app.component.html

<div class="container">
<div class="form-group col-sm-3">
          <label for="">PDF file</label>
          <input type="file"  (change)="fileChange($event)" accept=".pdf">
        </div>
    <div class="row">
        <div class="col-md-5">
            <div class="thumbnail" style="width: 150px;height: 200px;">
                <pdf-viewer [src]="pdfSrc"
                            [page]="page"
                            [original-size]="false"
                            style="display: block;"
                 ></pdf-viewer>
            </div>
            <br>
        </div>
    </div>
</div>

app.component.ts

import { Component } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  pdfSrc;
  loaded;
  ngOnInit() {
  }

  file: File;
  fileChange(event) {
    let fileList: FileList = event.target.files;
    if (fileList.length > 0) {
     this.handleInputChange(event);
    }
  }

  handleInputChange(e) {
        this.file = e.dataTransfer ? e.dataTransfer.files[0] : e.target.files[0];

        var reader = new FileReader();

        this.loaded = false;
        reader.onload = this._handleReaderLoaded.bind(this);
        reader.readAsDataURL(this.file);
    }

     _handleReaderLoaded(e) {
        var reader = e.target;
        this.pdfSrc = reader.result;
        this.loaded = true;
    }

}

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

Practice with Angular - Testing asynchronous service calls

Encountering an issue with the code while attempting to check the DOM element. I have used ngIf with a service async call in HTML, and the sample code is provided below: <div class="" *ngIf="EmployeeService.employees$ | async"> <div class="h ...

The issue of binding subjects in an Angular share service

I established a shared service with the following Subject: totalCostSource$ = new Subject<number>(); shareCost(cost: number ) { this.totalCostSource$.next(cost); } Within my component, I have the following code: private incomeTax: num ...

To allow users to sign in, the mutation can be filtered based on the boolean value of `isVerified

How can I filter and only allow users with isVerified === true to sign in? If it's false, the user should not be able to sign in through the mutation. Here is my code for the mutation: signin: async ( _: any, { credentials }: SignInArgs, ...

Error 401: Access Denied for @angular/cli@latest - Version Angular 7.0.4

Today when I started working on my project, I encountered an error that said: ERROR TypeError: Cannot read property 'whitelist' of undefined at isFiltered (:1:5016) at Object.x [as send] (:1:74196) at DevtoolsExtension.push../node_modules/@ngrx/s ...

Converting JQueryPromise to Promise: A step-by-step guide

In my current project, there is a code snippet that produces a JQuery promise: const jqProm = server.downloadAsync(); I am interested in integrating this promise within an async function. I was thinking of creating something similar to the C# TaskComplet ...

utilize a document within ngx Translate

I've been working on transitioning an app from AngularJS to Angular 4. As I gradually move components over, I'm encountering issues with translation. My goal is to continue using the old AngularJS translation alongside ngx-translate. Prior to ...

Angular reactive forms allow you to create dynamic forms with fields that change

Consider the following data structure: formAviso: FormGroup; deapartamentos: [ {nombre: 'Amazonas', codigo: 41}, {nombre: 'Ancash', codigo: 43}, {nombre: 'Apurimac', codigo: 83}, ... ] constructor() { this.formAvi ...

Conceal the PayPal Button

Currently, I'm facing a challenge where I need to dynamically show or hide a PayPal button based on the status of my switch. The issue is that once the PayPal button is displayed, it remains visible even if the switch is toggled back to credit card pa ...

Angular 5 Custom validators: Error message - 'passwordG' is not defined in ng

Currently working with Angular 5 and attempting to create custom validators for password inputs along with a confirmation password field. This is the HTML code : <div formGroupName = "passwordG"> <div class="form-group"> <label ...

Is there a way to expand the return type of a parent class's methods using an object

Currently, I am enhancing a class by adding a serialize method. My goal is for this new method to perform the same functionality as its parent class but with some additional keys added. export declare class Parent { serialize(): { x: number; ...

Issues with Angular event binding not meeting the expected functionality

I'm currently working on a form that includes fields for usernames and email addresses. Alongside these, I have a separate field where I want the text input by the user to be displayed. I'm facing an issue with event binding within the form – i ...

Error: Attempting to access an undefined property ('call') on Next.js is causing a TypeError

Exploring the realms of Next.js and Typescript for a new project! My goal is to utilize next.js with typescript and tailwind CSS by simply entering this command: npx create-next-app -e with-tailwindcss my-project Smooth sailing until I hit a snag trying t ...

When using the `.push` method, the array becomes null

Currently, I am in the process of developing an angular application. Within my component's .ts file, there exists an array structured as follows: public myArray = []; public dataFromAPI = []; In a particular method within this component, whenever I ...

Encountering a "is not a function" error in NextJS while attempting to import a custom hook

Exploring the world of NextJS, I am embarked on creating a responsive website starting with a navigation bar component. The goal is to ensure that it adapts seamlessly to different viewport dimensions. Let me walk you through my current folder structure: h ...

Update the input component's typing area line color from its default shade

Is there a way to customize the color of the line in the typing area for the input component? I haven't been able to find any information on using Sass variables or another method to achieve this. For reference, here is a Plunker example <ion-it ...

Storage in Ionic and variable management

Hello, I'm struggling to assign the returned value from a promise to an external variable. Despite several attempts, I have not been successful. export class TestPage { test:any; constructor(private storage: Storage) { storage.get('t ...

Position of the item in an array that contains an array with only one item

Currently, I am utilizing the Google Maps API in Angular with TypeScript. My goal is to create a clickable map of countries that changes color when clicked. This task seems simple, but I am encountering a challenge due to the complexity of the ng2-google-m ...

Developing a function that takes a parameter which can be used with or without an additional argument when invoked

In my React application, I have a method that accepts a parameter for displaying a modal. const displayModal = (p:Result) => { setConfirm(true); if(p) { //check variable for truthy setSelectedRow(p); } ...

Tips for displaying HTML content dynamically in React using TypeScript after setting a stateVariable

To render an HTML block after successfully setting a state variable, I have defined my state variables and functions below. The code snippet is as follows: const formService = new FormService(); const [appointmentDate, setAppointmentDate] = us ...

Angular 5 offers the ability to incorporate dynamic checkbox input into your application

Here is my code snippet: <input [type]="'checkbox'" [(ngModel)]="inputValue"> <p>Value: {{ inputValue }}</p> I'm puzzled as to why the value in inputValue remains unchanged. Can anyone shed light on this? I am unable to ...