Issue encountered while trying to upload an image with Angular Material framework

I'm a beginner with angular material and I'm struggling to get any image I upload to take the position of my avatar image. Firstly, the avatar image isn't showing up at all and secondly, when I try to upload an image, it doesn't display on the page.

HTML


 <div class="select-image">
        <img [src]="imgSource" class="circle hims-orange" [class.circle]="circle" alt="Avatar" (click)="select.click()">
        <button mat-mini-fab color="accent" matTooltip="Add Image" class="select-btn" type="button" (click)="select.click()">
            <mat-icon>add_a_photo</mat-icon>
        </button>
        <input type="file" accept="image/gif, image/jpeg, image/png" #select hidden (change)="imageChanged($event)" />
    </div>

ts

imageChanged(imgSource?: MatCardImage): void {
    this.image = this.imgSource
    console.log('working')
  };

the button

Answer №1

Here is an example of Angular Material Image Upload for you:

upload-image.component.html:

<div *ngFor="let progressInfo of progressInfos">
  <span>{{ progressInfo.fileName }}</span>
  <mat-toolbar class="progress-bar">
    <mat-progress-bar
      color="accent"
      [value]="progressInfo.value"
    ></mat-progress-bar>
    <span class="progress">{{ progressInfo.value }}%</span>
  </mat-toolbar>
</div>

<mat-form-field>
  <div>
    <mat-toolbar>
      <input matInput [value]="selectedFileNames.length ? selectedFileNames : 'Select Images'" />

      <button
        mat-flat-button
        color="primary"
        [disabled]="!selectedFiles"
        (click)="uploadFiles()"
      >
        Upload
      </button>
    </mat-toolbar>

    <input
      type="file"
      id="fileInput"
      name="fileInput"
      accept="image/*" multiple 
      (change)="selectFiles($event)"
    />
  </div>
</mat-form-field>

<div>
  <img *ngFor='let preview of previews' [src]="preview" class="preview">
</div>

<div *ngIf="message.length" class="message">
  <ul *ngFor="let msg of message; let i = index">
    <li>{{ msg }}</li>
  </ul>
</div>

<mat-card class="list-card">
  <mat-card-header>
    <mat-card-title>List of Images</mat-card-title>
  </mat-card-header>
  <mat-card-content>
    <mat-list role="list">
      <mat-list-item role="listitem" *ngFor="let image of imageInfos | async" class="list-item">
        <p matLine><a href="{{ image.url }}">{{ image.name }}</a></p>
        <img src="{{ image.url }}" alt="{{ image.name }}" height="50px"/>
      </mat-list-item>
    </mat-list>
  </mat-card-content>
</mat-card>

upload-imges.component.ts:

import { Component, OnInit } from '@angular/core';
import { HttpEventType, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { FileUploadService } from '../../services/file-upload.service';

@Component({
  selector: 'app-upload-images',
  templateUrl: './upload-images.component.html',
  styleUrls: ['./upload-images.component.css']
})
export class UploadImagesComponent implements OnInit {
  selectedFiles?: FileList;
  selectedFileNames: string[] = [];

  progressInfos: any[] = [];
  message: string[] = [];

  previews: string[] = [];
  imageInfos?: Observable<any>;

  constructor(private uploadService: FileUploadService) {}

  ngOnInit(): void {
    this.imageInfos = this.uploadService.getFiles();
  }

  selectFiles(event: any): void {
    this.message = [];
    this.progressInfos = [];
    this.selectedFileNames = [];
    this.selectedFiles = event.target.files;

    this.previews = [];
    if (this.selectedFiles && this.selectedFiles[0]) {
      const numberOfFiles = this.selectedFiles.length;
      for (let i = 0; i < numberOfFiles; i++) {
        const reader = new FileReader();

        reader.onload = (e: any) => {
          console.log(e.target.result);
          this.previews.push(e.target.result);
        };

        reader.readAsDataURL(this.selectedFiles[i]);

        this.selectedFileNames.push(this.selectedFiles[i].name);
      }
    }
  }

  upload(idx: number, file: File): void {
    this.progressInfos[idx] = { value: 0, fileName: file.name };

    if (file) {
      this.uploadService.upload(file).subscribe(
        (event: any) => {
          if (event.type === HttpEventType.UploadProgress) {
            this.progressInfos[idx].value = Math.round(
              (100 * event.loaded) / event.total
            );
          } else if (event instanceof HttpResponse) {
            const msg = 'Uploaded the file successfully: ' + file.name;
            this.message.push(msg);
            this.imageInfos = this.uploadService.getFiles();
          }
        },
        (err: any) => {
          this.progressInfos[idx].value = 0;
          const msg = 'Could not upload the file: ' + file.name;
          this.message.push(msg);
        }
      );
    }
  }

  uploadFiles(): void {
    this.message = [];

    if (this.selectedFiles) {
      for (let i = 0; i < this.selectedFiles.length; i++) {
        this.upload(i, this.selectedFiles[i]);
      }
    }
  }
}

Take a look at the live Stackblitz demo here.

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

Can someone guide me on how to align text to the bottom border of a page?

Is there a way to adjust the position of the header text ("bottom text") so that it appears just above the bottom border of the page? I have attempted modifying styles and classes within the footer, style, and h3 tags but have not had any success. Below ...

Error message: NullInjectorError: R3InjectorError[ToastrService -> ToastrService -> InjectionToken ToastConfig -> InjectionToken ToastConfig]:

I'm struggling with integrating ngx-toastr into my Angular standalone micro-frontend in angular 16. When I try to add the ngx-toastr provideToast() function in the main Module component, it doesn't seem to work as expected. Can someone please hel ...

I'm attempting to incorporate the CSS file into the main HTML template, but the styling isn't being applied. My goal is to define the styles externally

The CSS style isn't being properly imported. Below is the base HTML file (base.html) I'm using: <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <meta name="viewport" content="widt ...

Is there a way to implement fixed scrolling on a website?

I'm interested in implementing fixed scrolling on a webpage similar to the effect used here: . When you scroll on that website, it smoothly transitions to the next div. I believe there is some JavaScript involved, but I am not sure how to achieve thi ...

Triggering functions when the mouse wheel is in motion

I am new to utilizing javascript and jquery, and my knowledge is limited at the moment. I am attempting to create a script that will trigger different functions based on the direction of mouse wheel movements in a way that works across various programs. Ca ...

Deno.Command uses backslashes instead of quotes for input containment

await new Deno.Command('cmd', { args: [ '/c', 'start', `https://accounts.spotify.com/authorize?${new URLSearchParams({ client_id, response_type: 'code', ...

Cart filled with desired items but no payment necessary

Hey there! I'm currently working on building a static website using HTML and CSS. While I don't have knowledge of Javascript or PHP, I am able to incorporate jQuery into websites by simply copying and pasting the code in the right place. I was w ...

Is it possible to use string indexes with jQuery each method in Typescript?

When running a jQuery loop in Typescript, I encountered an issue where the index was being reported as a string. $.each(locations, (index, marker) => { if(this.options && this.options.bounds_marker_limit) { if(index <= (this.opt ...

How to Style an Element Based on Fragment Identifier in Href Attribute Using CSS

I've implemented the tabview feature from the YUI3 library. This is how the markup code appears: <div id="demo" class="yui3-tabview-content"> <ul class="yui3-tabview-list"> <li class="yui3-tab yui3-widget yui3-tab-selected"> ...

What are the parameters that are affected by the noImplicitAny compiler flag?

The TypeScript documentation details the significance of the noImplicitAny compiler flag, which is designed to: Flag errors on expressions and declarations that have an implicit any type. Consider the code snippet below: let x; // x is impl ...

Placing one image on top of another in an email layout

Is there a way to position an element in any email template? I need to place an image over another one, which can only be done by either positioning it absolutely or giving it a margin. However, I've heard that Google doesn't support margin and p ...

Is it Possible to Modify CSS Dynamically within an Angular Directive?

I am currently developing a directive for an input field of type text. My goal is to have the width of this field expand dynamically if the text exceeds the size of the input field. Below is the code snippet for my directive: .directive('dynamicInput ...

Is there a way to apply toggling and styles to only the card that was clicked in Vue.js?

DisplayBooks.vue consists of a single page responsible for showcasing books fetched from a backend API. Each card on the UI features two buttons - ADD TO BAG and ADDED TO BAG. When a user clicks on the ADD TO BAG button of a specific card, it should toggle ...

Can the geocoder API/search box be utilized to locate specific markers on a map?

Incorporating Mapbox into an Angular application with a high volume of markers on the map (potentially thousands) and hoping to implement a search box for users to easily locate specific markers based on unique names and coordinates. Is this functionalit ...

Establishing a color palette for various CSS classes using a gradient color spectrum

I am looking to create a gradient color scale and define classes for it based on a range of values. My scale ranges from 0 to 8.5, with increments of 0.25. This means I have a total of 34 different colors (8.5/0.25 = 34) to cover the entire spectrum. Each ...

Having difficulty storing duplicate requests that are crucial for various services/components

Currently, I am tackling a project that involves displaying multiple sets of data to the user. Each set requires several requests to be made to the backend. Specifically, for the UserDetails dataset, I must query the getUser and getSigns endpoints. However ...

jQuery if statement appears to be malfunctioning

When the condition operates alone, everything works fine. However, when I introduce an 'and' operation, it does not function correctly. If only one of them is true, the code works. It also successfully takes input values. <!DOCTYPE HTML Code ...

Learn how to effectively utilize the onload event in Angular 2 when working with dynamically inserted image sources

How do I set specific flags once an image finishes downloading? I attempted to use the onload event on the image tag and call a function. However, the implementation below is throwing an error: Uncaught ReferenceError: imageLoaded is not defined ...

Eliminate the routerLinkActive attribute that assigns two classes when the user switches to a different menu

As I develop a Web Application using Angular 6, I encounter an issue with implementing routerLink and routerLinkActive. While routerLink works properly, the routerLinkActive does not seem to function as expected. It retains the class within the tag even wh ...

Configuring the React Typescript router to support username-based URLs should be done in a way that does not cause conflicts with other routes

I am looking to display a user's profile on a URL format such as www.domain.com/<userName> and load the component ShowProfile. I want to ensure that terms is not mistaken for a username, so if I visit www.domain.com/terms, I do not want to load ...