Angular 5 Image Upload Tool

Looking for an image uploader in Angular 5, I struggled to find the perfect one. Eventually, I came across a suitable option in JavaScript, but I need to use it in TypeScript instead.

Here is a snippet of the HTML code:

<div class="avatar-upload">
    <div class="avatar-edit">
        <input type='file' id="imageUpload" accept=".png, .jpg, .jpeg" />
        <label for="imageUpload"></label>
    </div>
    <div class="avatar-preview">
        <div id="imagePreview" style="background-image: 
       url(http://i.pravatar.cc/500?img=7);">
        </div>
    </div>
</div>

And here are some CSS styling details:

body {
  background: whitesmoke;
  font-family: 'Open Sans', sans-serif;
}

.container {
    max-width: 960px;
    margin: 30px auto;
    padding: 20px;
}
...

In terms of JavaScript functionality:

function readURL(input) {
 if (input.files && input.files[0]) {
    var reader = new FileReader();
    ...
    }
    reader.readAsDataURL(input.files[0]);
 }
}
$("#imageUpload").change(function() {
    readURL(this);
});

I am wondering how I can utilize this setup in Angular 6. If you have any insights or solutions, please share them with me. You can also check out the original source here.

Answer №1

When working with typescript, the code snippet below demonstrates how to handle file uploads.

<input type="file" id="upload-photo" style="display: none" (change)="onSelectFile($event)" />

    onSelectFile(event: any) {
        if (event.target.files && event.target.files[0]) {
            const reader = new FileReader()

            reader.onload = (ev: any) => {
                this.person.photo = ev.target.result
            }
            reader.readAsDataURL(event.target.files[0])

        }
    }

To display the uploaded file in HTML, utilize two-way data binding.

Alternatively, refer to this link for more information:

https://stackblitz.com/edit/angular-twk2pn?file=src%2Fapp%2Fapp.component.ts

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

Dependencies between libraries within a workspace

Recently, I set up a brand new Angular 6 workspace that includes an application along with two libraries: library1 and library2. library2 depends on a module from library1, as shown below import {Library1Module} from "library1" I successfully compiled li ...

Is there a mistake in the TypeScript guide for custom typography in MUI5?

Currently, I am in the process of setting up custom typography variants in MUI5 by referencing this helpful guide: https://mui.com/customization/typography/#adding-amp-disabling-variants. As I follow step 2 and input the type definitions: declare module &a ...

What are the best practices for effectively using RxJs subscriptions?

I'm looking for some advice on how to handle Angular and RxJs mechanics. I have server-side pagination set up on my backend and three components on the frontend: a data list, filters, and a pagination component. How can I subscribe to two streams (pag ...

Guide on incorporating the handsontable library with Angular 2

As I delve into the realm of configuration in npm, I am attempting to integrate the handsontable library into an Angular 2 project built with angular-cli (ng init). I have included the TypeScript definition for the library as well. Below is the content of ...

The request.files property in express-fileupload is consistently coming back as undefined

I am trying to achieve the task of uploading a file from my browser and sending it via POST to an Express.js application, which will then download the file using express-fileupload. Here is the client-side JavaScript code I have written so far: // Triggere ...

Tips for importing modules without encountering errors

Currently in the process of constructing a compact website with socket.io and express. Opting for Typescript to ensure accurate type errors, then transpiling the frontend code to Javascript for seamless browser execution. Frontend code: import { io, Socke ...

Creating an array of custom objects in JavaScript.Initializing custom objects in an

Is there a proper way to prevent the error "Cannot read property 'length' of undefined" when initializing an array of custom objects in javascript? situation export class MyClass implements OnInit { myArray: MyObject[]; } example <div ...

Creating personalized functions in Object.prototype using TypeScript

My current situation involves the following code snippet: Object.prototype.custom = function() { return this } Everything runs smoothly in JavaScript, however when I transfer it to TypeScript, an error surfaces: Property 'custom' does not ex ...

Angular 2: Change Boolean value depending on a condition

I find myself facing a challenge with a search-bar feature. My goal is to display all the filtered names when the input value reaches a length of 2 or more characters. After successfully extracting the value.length from the input field, I encountered a ro ...

Using Node.js and Typescript to bring in external modules from

Attempting to generate a random integer between 1 and 6 using the 'random' library. Here's what I have coded so far: import random from 'random' function rollDice(min:number, max:number) { return Math.floor(Math.random() * (ma ...

Navigating away from the IdentityServer page within the Angular SPA in an ASP.NET Core application triggers a refresh of the entire

My ASP.NET Core Angular SPA app is integrated with IdentityServer 4. Whenever I navigate to the Identity pages (such as Manage Account) and then return to my app (by clicking the Home link or Back button), the website reloads. Is this normal behavior? Can ...

Unable to perform navigation during page load in a React.js application

I attempted to navigate to a route that should redirect the user back to the homepage when postOperations isn't set in the localStorage. To save time, please review the code snippet focusing on the useEffect and the first component inside return(). im ...

"ENUM value is stored in the event target value's handle property

My issue lies with the event.target.value that returns a 'String' value, and I want it to be recognized as an ENUM type. Here is my current code: export enum Permissions { OnlyMe, Everyone, SelectedPerson } ... <FormControl> & ...

The JSX component cannot utilize 'Home' when working with React and TypeScript

I am a beginner in using React and TypeScript, and I want to retrieve data from an API and display it in a table using TypeScript and React. My project consists of two files: Home.tsx and App.tsx. The primary code that interacts with the API is located in ...

When it comes to rendering components in React using multiple ternary `if-else` statements, the question arises: How can I properly "end" or "close" the ternary statement?

I have developed a straightforward component that displays a colored tag on my HTML: import React, {Component} from 'react'; import "./styles.scss"; interface ColorTagProps { tagType?: string; tagText?: string; } /** * Rende ...

A step-by-step guide on sending GET requests in sequence using nested observables

I've been working on creating a dynamic filter that allows users to sort a list of elements by clicking on ion-chips. Each click triggers a call to an external backend using rxjs, with the responses being used sequentially to update the list of elemen ...

Angular2 RC1 route parameters with periods in them

When working with a child component, I often use paths similar to the following: @Routes([ { path: '/axis/:prefixPath', component: AxisComponent }, ... ]) An example of a resulting link is: http://localhost:3000/parent/axis/foo.bar Th ...

Creating a universal timer at the application level in Angular

Is there a way to implement a timer that will automatically execute the logout() function in my authentication.service at a specific time, regardless of which page I am currently on within my application? I attempted to create a timer within my Authentica ...

Inheritance of Type Member in TypeScript

My data structure looks like this: export abstract class Person { ... } export class FPerson extends Person { a: A; b: B; } export class JPerson extends Person { c: C; } export class User { person: Person; } When dealing with the s ...

Apply a see-through overlay onto the YouTube player and prevent the use of the right-click function

.wrapper-noaction { position: absolute; margin-top: -558px; width: 100%; height: 100%; border: 1px solid red; } .video-stat { width: 94%; margin: 0 auto; } .player-control { background: rgba(0, 0, 0, 0.8); border: 1px ...