Tips for showcasing both PDF and image files in a single Angular4 component

Recently, I ventured into the world of angular4 and encountered an issue while attempting to showcase both a pdf file and an image file within a component.

The problem I faced is as follows:

Whenever I select an image, it displays correctly. However, when I choose a pdf file, the selected image is replaced, and the pdf file does not get displayed at all.

If you would like to take a look at my code on StackBlitz, here is the link: https://stackblitz.com/edit/angular-rq5ro5?file=src%2Fapp%2Fquestions-stepper%2Fquestions-stepper.component.html

I would greatly appreciate any assistance in resolving this issue.

HTML

<!-- Image File -->

<button class="col-sm-12 stylings" 
mat-raised-button (click)="file.click()">{{caption}}</button>
<input hidden type="file" accept="image/*" #file onclick="this.value = null" (change)="onSelectFile($event)">
<mat-card class="col-sm-12" style="padding:4px">
<div style="display: flex;align-items: center;justify-content: center;">
<img [src]="selectedImage" class="img-responsive img" /></div>
</mat-card>

  <!-- Pdf File -->

  <button class="col-sm-12 stylings" 
mat-raised-button (click)="file.click()">{{captionPdf}}</button>
<input hidden type='application/pdf' accept="application/pdf" #file1 onclick="this.value = null" (change)="onSelectPdfFile($event)">
<mat-card class="col-sm-12" style="padding:4px">
<div style="display: flex;align-items: center;justify-content: center;">
<img [src]="selectedPdf" class="img-responsive img" /></div>
</mat-card>

typescript

 onSelectFile(event) {
    if (event.target.files && event.target.files[0]) {
      this.imageToUpload = event.target.files[0];
      const reader = new FileReader();
      reader.readAsDataURL(this.imageToUpload);
      reader.onload = e => this.selectedImage = reader.result.toString();
      this.caption = event.target.files[0].name;
    }
  }

onSelectPdfFile(event) {
    if (event.target.files && event.target.files[0]) {
      this.imageToUpload = event.target.files[0];
      const reader = new FileReader();
      reader.readAsDataURL(this.imageToUpload);
      reader.onload = e => this.selectedPdf = reader.result.toString();
      this.caption = event.target.files[0].name;
    }
  }

Answer №1

To access the PDF section, make sure to trigger file1.click(). Additionally, adjust the input type to 'file.'

<button class="col-sm-12 stylings" 
mat-raised-button (click)="file1.click()">{{captionPdf}}</button>
<input hidden type='file' accept="application/pdf" #file1 onclick="this.value = null" (change)="onSelectPdfFile($event)">

Utilize in order to display a preview of the PDF document.

<iframe [src]="sanitizer.bypassSecurityTrustResourceUrl(selectedPdf)" width="200px" height="200px"></iframe></div>

Access the StackBlitz link for demonstration: https://stackblitz.com/edit/angular-pcirtt?file=src%2Fapp%2Fquestions-stepper%2Fquestions-stepper.component.html

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

What's the best way to use Flexbox to center a component with a "fixed width"?

As I work on my component, here is the code snippet from my highest parent, App.component: app.component.html <div class="wrapper_flex"> <div style="width:400px; background-color: pink;"></div> <div style=& ...

How to pass a variable from a template to a TypeScript file in Angular upon clicking a button

Having a component with a getter function that iterates through an object using forEach, accessing variables in the HTML file is easy. However, encountering trouble when trying to pass one of the variables in another function through a button click. Despit ...

Modify the key within an array of objects that share a common key

I have an object structured as follows: NewObjName: Object { OLDCOLUMNNAME1: "NEWCOLUMN_NAME1", OLDCOLUMNNAME2: "NEWCOLUMN_NAME2", OLDCOLUMNNAME3: "NEWCOLUMN_NAME3"} Next, there is an array containing objects in this format: ...

What is causing the TypeScript error in the MUI Autocomplete example?

I am attempting to implement a MUI Autocomplete component (v5.11) using the example shown in this link: import * as React from 'react'; import TextField from '@mui/material/TextField'; import Autocomplete from '@mui/material/Autoco ...

Leveraging TypeScript alongside body-parser to access properties within req.body

I'm currently developing a web application using TypeScript and integrating the body-parser middleware to handle JSON request bodies. I've encountered type errors while attempting to access properties on the Request.body object. For instance, wh ...

Tips for customizing the color of a leaflet-routing-machine marker

I'm currently utilizing the leaflt-routing-machine plugin, and I'm looking to alter the color of markers from blue to red. Any ideas or suggestions on how to achieve this?! ...

The validation process in Redux forms

Imagine we have the following types defined: interface MyFormFields { FirstName: string; LastName: string; } type FieldsType = keyof MyFormFields; const field1: FieldsType = "c"; const field2 = "c" as FieldsType; Now, I am looking to implemen ...

What is the reason behind TypeScript permitting the assignment of a class instance to a variable that is of a different type?

When examining the given code, it raises a question about why the TypeScript compiler permits the assignment const c1: I = new C();. The issue arises when the function call c1.z(args); results in an error due to the absence of the first property in the a ...

Acquire Binance account balances through NextJS, ccxt library, and TypeScript integration

Currently, I am attempting to retrieve balances from Binance within my NextJS 13 application, utilizing the /src/app directory along with TypeScript. async function fetchData() { const exchange = new ccxt.binance ({ "apiKey": "mykey ...

What is the best way to choose a file path for the saveAs() function in JavaScript or TypeScript?

Q1: What is the method for defining the path when using the saveAs() function in JavaScript? After downloading a file, I want to be able to specify a path like: C:\Users\file-\projectName\src\assets\i18n\en.json const b ...

Challenges faced when integrating Angular with Bootstrap elements

I am currently in the process of developing a website using Angular 12, and although it may not be relevant, I am also incorporating SCSS into my project. One issue that I have encountered pertains to the bootstrap module, specifically with components such ...

Show a table row based on a specific condition in Angular

I'm having this issue with the tr tag in my code snippet below: <tr *ngFor="let data of list| paginate:{itemsPerPage: 10, currentPage:p} ; let i=index " *ngIf="data.status=='1'" > <td> </td> <td> ...

Unleashing the power of ::ng-deep to access CSS in an Angular child component

I'm attempting to modify the CSS class of a child component by using ::ng-deep. Despite my efforts with various iterations of the code provided below, I have been unsuccessful in accessing the CSS. The structure of the HTML component is depicted in th ...

merge the states of two Redux stores

I have two different stores in my system - one for properties and another for owners. Each property can be owned by one or more owners, and I need to organize the properties based on their respective owners, essentially creating a map structure like Map< ...

WebStorm is struggling to interpret the syntax of Angular 2

After setting up a new project in Angular CLI and using WebStorm, I've noticed that the IDE doesn't recognize Angular 2 syntax such as *ngFor and lacks autocomplete features for it. https://i.sstatic.net/wwxXQ.png Seeking assistance on enabling ...

Using Angular Material's [mat-form-field], you can easily input a value into a text box

How can I programmatically add a value to a text box within a [mat-form-field] using a function? addValueToTextBox(){ ... } ...

Ways to populate the second nested array with new values without overwriting existing ones

I am encountering the following issue: this.logs = {}; this.logs[1] = resp; In my initial array, I have the result shown in the image below: https://i.sstatic.net/RScSm.png However, when I try to add a second level array with another array like this: th ...

Identifying Typescript argument types

The given code is functional, but I am looking to refactor it for better clarity using Typescript syntax if possible. class Actions { actions: string[] } type Argument = object | Actions; export class GetFilesContext implements IExecutable { execute( ...

What is the best way to transform a string into a template reference object?

In the process of setting up ngTemplateOutlet within *ngFor, I encountered an issue similar to that outlined in the code snippet below. <ul> <li *ngFor="let item of list"> <ng-container [ngTemplateOutlet]="item.type"></ng- ...

How to Switch to a Different Tab in a NativeScript TabView

I'm struggling to figure out how to programmatically navigate to a different tab within a tabView from a partial View. Each tab is located in a child folder with its own html, ts, js, and css files. In this scenario, when a user clicks on an item in a ...