"Users have reported that the file upload preview feature in Angular 6 only works after the

I am currently utilizing Angular 6.

In my application, I have a simple input type="file" field that passes data to an image source which displays the image I intend to upload.

The issue I am facing is that when I select an image for the first time, nothing happens. However, when I choose an image for the second time, the preview of the image appears successfully.

What could be causing this behavior? Why am I unable to see the image preview on the first selection?

Here is my HTML code:

<div class="container" class="border">
    <div class="row">
        <div class="col-md-6 offset-md-3">
            <h3>Choose File</h3>
            <form (ngSubmit)="onSubmit()">
                <span style="color:red;" *ngIf="message">{{message}}</span>
                <input #file type="file"  ngf-max-size='10' accept='image/*' name="image" (change)="preview(file)">
                <img [src]="imgURL" height="200" width="200" *ngIf="imgURL">
                <div class="form-group">
                    <button class="btn btn-primary">Submit</button>
                </div>
            </form>
        </div>
    </div>
</div>

And here is my TypeScript code:

export class BottomSheetComponent implements OnInit {

  token = this.pzLogin.userLoginAccessToken;
  public imagePath;
  imgURL: any = this.pzLogin.UserLoginClaims.ImageUrl;
  public message: string;
  fileData = new FileReader();

  constructor(
    private _bottomSheetRef: MatBottomSheetRef<BottomSheetComponent>,
     private http: HttpClient, private pzLogin: PrivateZoneLoginService,
     private localStorageService: LocalStorageService) { }

 /* openLink(event: MouseEvent): void {
    this._bottomSheetRef.dismiss();
    event.preventDefault();
  }*/

  ngOnInit() {

  }

  preview(event) {

    if (event.files.length === 0) {
      return;
    }

    const mimeType = event.files[0].type;
    if (mimeType.match(/image\/*/) == null) {
      this.message = 'Only images are supported.';
      return;
    }

    const fileSize = event.files[0].size;
    if (fileSize > 200839) {
      this.message = 'Maximum upload file size 200 kb.';
      return ;
    }

    const reader  = new FileReader();
    reader.readAsDataURL(event.files[0]);

    reader.onload = () => {
    this.imgURL =  reader.result;
    this.fileData = event.files;
    };
  }

  onSubmit() {
    const formData = new FormData();
   formData.append('UploadedFile', this.fileData[0], this.fileData[0].name);
   formData.append('token', this.token);
    this.http.post('http://localhost:11111/PrivateZone/UploadUserImage', formData)
      .subscribe(res => {
        console.log('res' + res);
        this.localStorageService.setItem('UserLoginClaims', res);
      });
  }
}

Answer №1

Give this a try:

 displayPreview(event) {

    if (event.files.length === 0) {
      return;
    }

    const fileType = event.files[0].type;
    if (fileType.match(/image\/*/) == null) {
      this.message = 'Please upload only images.';
      return;
    }

    const fileSize = event.files[0].size;
    if (fileSize > 200839) {
      this.message = 'Maximum file size allowed is 200 kb.';
      return;
    }

    const reader = new FileReader();
    reader.readAsDataURL(event.files[0]);

    const that = this; // setting reference of this to that
    reader.onload = () => {
        that.imageURL = reader.result;
        that.uploadedFile = event.files;
    };
}

Please let me know if this solution works for you.

Answer №2

When dealing with the Bottom Sheet component and uploading an image, I encountered a problem.

The solution was simple, just include

this._bottomSheetRef.containerInstance.enter();

Executing this line of code will successfully load the image.

Below is the revised code snippet:

  this.reader.onload = () => {
      this.imgURL = this.reader.result;
       this.fileData = event.files;
       this._bottomSheetRef.containerInstance.enter();
    };

Answer №3

Give this a try

checkInput(event) {

    if (event.files.length === 0) {
        return;
    }

    const fileType = event.files[0].type;
    if (fileType.match(/image\/*/) == null) {
        this.message = 'Please select only images.';
        return;
    }

    const fileSize = event.files[0].size;
    if (fileSize > 200839) {
        this.message = 'File size should not exceed 200 kb.';
        return ;
    }

    const fileReader  = new FileReader();
    fileReader.readAsDataURL(event.files[0]);

    const _that = this;
    fileReader.onload = () => {
        _that.imageURL =  fileReader.result;
        _that.selectedFile = event.files;
    };
 }

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

Execute the function upon clicking

When I click on an icon, I want it to blink. This is the code in my typescript file: onBlink() { this.action = true; setTimeout(() => { this.action = false; }, 1000) return this.action }; Here is how the action is declared in my ...

Where can I find the Cypress.json file for Angular integration with Cypress using Cucumber?

We are currently transitioning from Protractor to Cypress utilizing Cucumber with the help of cypress-cucumber-preprocessor. While searching for Angular documentation on this setup, including resources like , all references lead to an automatically generat ...

Incorporating an interface into a data property within a router using TypeScript and Angular

Within the app-routing-module.ts file, utilizing the data property allows us to include custom fields/variables as shown below: ... { path: 'admin-board', loadChildren: './admin-board/admin-board.module#AdminBoardPageModule', dat ...

angular-in-memory-web-api encounters a 404 error

I recently completed the heroes tour and now I am trying to work on something similar, but I seem to be having trouble understanding angular-in-memory-web-api. Here is a snippet of my code: clients-data.service.ts import { Injectable } from '@angular/ ...

Dealing with custom path problems in Angular 2+ webpack configurations

I am interested in using the @ngneat/tailwind schematics to convert an Angular project into one with a custom webpack configuration. However, after adding this, my scss import paths for fonts and other partial scss files are not resolving, resulting in th ...

Utilizing Node modules in TypeScript, Angular 2, and SystemJS: A Comprehensive Guide

In the process of developing a simple Angular 2 application, I am constructing a class named User. This class includes a function called validPassword() which utilizes the bcrypt library to validate user passwords: import { compareSync, genSaltSync, hashS ...

Tabs justified are not constrained by width

Utilizing Bootstrap 3, I aim to have the Tabs align perfectly with the full content. The use of nav-tabs can be observed in the code below. It may seem a bit unusual due to my implementation of Angular 4 and the code being copied from Dev Tools. <ul cl ...

What is the best way to incorporate Tradingview's JavaScript into the render function of a React Typescript

I'm trying to incorporate some widgets into my Typescript React component. Here is the embed code export default class App extends React.Component { render(): ReactNode { return ( <div> Chart test <div className= ...

What are the steps to update data in an md-table?

I'm currently working on a web application using Angular 4, but I'm facing an issue regarding the access to new data in my md-table. To better understand the problem, I have replicated the same example for my application. You can find the examp ...

Obtaining data attributes in Angular 8

I'm working with Angular 8 and I came across an issue. In my code snippet, there are two data attributes assigned to a button element, but only one attribute is showing up. Is this a syntax error or a bug? <button [attr.data-popolamento]="all" [a ...

The module 'PublicModule' was declared unexpectedly within the 'AppModule' in the Angular 4 component structure

My goal is to create a simple structure: app --_layout --public-footer ----public-footer.html/ts/css files --public-header ----public-header.html/ts/css files --public-layout ----public-layout.html/ts/css files In public-layout.html, the stru ...

Steps to automatically update a component when the button is clicked

Is there a way to change the displayed component in my parent component when clicking on a specific element? I currently have a pie chart component displaying by default but would like to switch it to another component with a different diagram when clickin ...

The error message "Angular 4 does not recognize the 'dragula' property as a valid property of the 'div' element" is displayed

Struggling to integrate ng2-dragula with the AspNetCore SPA template. Despite trying various solutions, I am still encountering the following error: Exception: Call to Node module failed with error: Error: Template parse errors: Can't bind to 'd ...

How to retrieve a stored value using Ionic 3 native storage

Hey there, I recently attempted to implement code from the Native Storage plugin documentation found at this link: Native Storage import { NativeStorage } from '@ionic-native/native-storage'; constructor(private nativeStorage: NativeStorag ...

Guide to creating two-way data binding using ngModel for custom input elements like radio buttons

I am currently facing an issue with implementing a custom radio button element in Angular. Below is the code snippet for the markup I want to make functional within the parent component: <form> <my-radio [(ngModel)]="radioBoundProperty" value= ...

Jasmine test case for Angular's for loop (Error: Expected the length of $ to be 11, but it should be 3

While creating test cases for a loop in Angular (Jasmine), I encountered an error: Error: Expected $.length = 11 to equal 3.. The loop is supposed to generate an array of arrays similar to const result. Can someone point out what I might have missed here? ...

The implementation of combineSlices in reduxjs/[email protected] is an essential feature for managing

I am struggling to figure out how to properly useAppSelector with LazyLoadedSlices: Here is the setup of my store // @shared/redux/store.ts // comment: https://redux-toolkit.js.org/api/combineSlices // eslint-disable-next-line @typescript-eslint/no-empty ...

How to access different state sections within a reducer using ngrx

If one state value changes, I want to remove another state value. How can I access other parts of the store from a reducer in NgRx? Here is my current store schema: a: {...} b: {...} I am trying to access the 'b' feature store from the ' ...

Error message: Injector Error: R3InjectorError(Standalone[_AppComponent])[_WebService -> _WebService -> _WebService] occurred

Being a student, I must apologize in advance for any mistakes in terminology or gaps in my understanding. I am currently developing an Angular front-end to communicate with my backend API. However, I keep encountering the following error in the web page c ...

Display a slideshow of images using the text and <img> tags found within a string in an Angular application

Currently, I am developing a blog system in Angular that involves utilizing a text editor component (ngx-text-editor) for inserting images and text. These images and text are then saved to the database. However, I am facing an issue when attempting to disp ...