What are the steps to update your profile picture using Angular?

In my Angular 6 application, I am implementing an image upload feature with the following code:

Html:

<img [src]="url ? url : 'https://www.w3schools.com/howto/img_avatar.png'"> <br/>
<input type='file' (change)="onSelectFile($event)">

Ts:

  onSelectFile(event) {
    if (event.target.files && event.target.files[0]) {
      var reader = new FileReader();

      reader.readAsDataURL(event.target.files[0]); // read file as data url

      reader.onload = (event) => { // called once readAsDataURL is completed
        this.url = event.target.result;
      }
    }
  }

Working stackblitz: https://stackblitz.com/edit/angular-file-upload-preview-ekyhgh

The current implementation allows users to select a file from their computer and display it as text, but I want the selected image to be displayed when clicking on the profile picture instead of the file input button. Additionally, I would like the ability to choose a file from the local folder upon clicking the profile image.

I found a similar functionality in this Codepen example: https://codepen.io/anon/pen/PXjaJv

On hover over the image, the text "Drag your photo here or browse your computer" appears. I aim to replicate this behavior by displaying the same text when hovering over any image to prompt users to change their profile picture.

Please disregard the cropping and dropping features in the provided Codepen link and focus solely on enhancing the UI by adding overlay text on hover and enabling the selection of images from the computer to change the profile picture, with an option to revert to the default avatar image if needed.

I'm seeking guidance on achieving this using pure Angular/TypeScript without relying on jQuery.

Answer №1

Ensure you utilize the label tag along with the appropriate for attribute. The for attribute should contain the id of the corresponding input tag.

Take a look at this example.

<label class="hoverable" for="fileInput">
  <img [src]="url ? url : 'https://www.w3schools.com/howto/img_avatar.png'"> 
  <div class="hover-text">Choose file</div>
  <div class="background"></div>
</label>
<br/>
<input id="fileInput" type='file' (change)="onSelectFile($event)">
<button *ngIf="url" (click)="delete()" >delete</button>

See an example in action on stackblitz.

Answer №2

While the answers provided above are accurate, I have a suggestion to add:

.css

p {
  font-family: Lato;
}

.image-container {
  position: relative;
  display: inline-block;
  text-align: center;
}

img {
  height: 200px;
  width: 200px;
  border: 5px solid #000;
  border-radius: 50%;
}

.select-profile-picture {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 999;
  opacity: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.message {
  position: absolute;
  width: 90%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, 100%);
  transition: all 1s;
  opacity: 0;
}

.image-container:hover .message {
  transform: translate(-50%, -50%);
  opacity: 1;
}

.html

<div class="image-container">
 <img [src]="url ? url : 'https://www.w3schools.com/howto/img_avatar.png'" class=""> <br/>
 <input type='file' (change)="onSelectFile($event)" class="select-profile-picture">
 <span class="message">Tap here to select your picture</span>
</div>

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 are the steps to downloading a server-generated image with user data from the client using Express?

I am facing a challenge with downloading a server-generated image immediately after it is created. My current approach involves using fetch to send user input data (bypassing HTML forms). Although the image is successfully generated on the server, I am str ...

Eliminate gaps created by grid rows by incorporating elements of varying heights

This is the standard format of the page: * { margin: 0; padding: 0; } img { width: 100%; float: left; } #grid { display: grid; grid-template-columns: repeat(3, 1fr); } #test-one { grid-column-start: 1; grid-column-end: 2; width: 100 ...

Embedding a thread in an HTML document (Difficult task)

I'm currently working on a method to achieve the following task: Embedding a specific string (such as "TEST") into the content of an HTML page, after every certain number of words (let's say 10). The challenge here is ensuring that the word count ...

Ways to retrieve form information from a POST request

I received a POST request from my payment gateway with the following form data: Upon trying to fetch the data using the code snippet below, I encountered errors and gibberish content: this.http .post<any>('https://xyz.app/test', { ti ...

What is the best way to dynamically write a knockout data binding event using jQuery?

let $button = $('<input/>').attr({ type: 'button', value: data.styleData, id: buttonId, data - bind: event: { click: $parent.submitPopUp } }); An error is being displayed. ...

Spinning and disappearing gradually over a set period of time

Could someone please help me with creating an animation for one of my CSS DIVs? I want it to have an exit/entry effect with rotation/fadeout and then rotation/fadein, with a 10-minute delay between each iteration. I'm not sure if this can be achieved ...

Exploring Angular2: A demonstration showcasing concurrent http requests (typeahead) using observables

Currently, I am working on several cases within my app that require the following sequence of events: Upon triggering an event, the desired actions are as follows: List item Check if the data related to that context is already cached; if so, serve cache ...

Creating an animated time-based scrollable bar chart in javascript

As someone who is new to JavaScript and charting, I am seeking assistance with a specific task. Despite browsing various JavaScript charting libraries and examples, none seem to address my issue: My goal is to generate dynamic stacked bar charts, as depic ...

NodeJS's pending ajax post using SailsJS

I'm experiencing an issue with processing AJAX data in my sailsJS app. The ajax post data always stays in the pending state, here is the code from my view: <script type="text/javascript"> $('#submit').click(function(){ $.ajax ...

Can the TEXT from a <select> be passed as the value of a hidden <input> element?

<form method="POST" action="question-function.php"> <label>Choose Category</label> <select name="catid" id="catid" class="form-control"> <?php $sel3 = mysqli_query($ ...

The RazorPay callback encountered an Uncaught TypeError indicating that the function is not recognized

In my TypeScript class, I have a defined handler as follows: "handler": function (response) { this.sendUserStatus(); }, Unfortunately, when I attempt to call this.sendUserStatus();, I encounter the following error: Uncaught Typ ...

Dynamic CSS sizing

Currently, I am in the process of creating a component and my goal is to achieve a specific layout without the use of JavaScript, preferably utilizing flexbox. Essentially, envision a messenger chat screen with a header and footer containing controls. htt ...

Removing div elements containing specific text using jQuery

Hello everyone, I am trying to remove all divs that contain a specific part of a string. Does anyone know how I can do this? This is what my original HTML looks like: <div class="article-options_4"></div> And this is the new HTML structure, ...

Is there a way to instantiate a new object within the same for loop without replacing the ones created in previous iterations?

My current issue with this exercise is that as I convert the first nested array into an object, the iteration continues to the next nested array and ends up overwriting the object I just created. I'm wondering how I can instruct my code to stop itera ...

`Generating an ever-changing masonry layout on a website using live data`

I'm currently working on a new web project and I want to incorporate a masonry view for the images on the homepage. The plan is to host this project on Azure, using blob storage for all the images. My idea is to organize the images for the masonry vi ...

Circular referencing in Angular models causes interdependence and can lead to dependency

I'm facing a dependency issue with the models relation in my Angular project. It seems to be an architecture problem, but I'm not sure. I have a User model that contains Books, and a Book model that contains Users. When I run this code, I encoun ...

Is it possible to schedule deployments using Vercel Deploy Hooks in Next.js?

When we schedule a pipeline on git, I want to schedule deploy hooks on vercel as well. Since the app is sending getStaticProps and every HTTP request will be run on every build, I have to rebuild the site to get new results from the server. For instance, ...

What is the method for obtaining the CSS text content from an external stylesheet?

I've spent countless hours trying to achieve the desired results, but unfortunately, I haven't been successful. Below is a summary of my efforts so far. Any helpful tips or suggestions would be greatly appreciated. Thank you in advance. Upon rec ...

Obtain the number of elements rendered in a React parent component from a switch or route

I'm currently working on a component that is responsible for rendering wrapper elements around its children. One challenge I'm facing is determining which elements are actually being rendered as children. I've implemented functions to ignore ...

The elements from base.html and the extended page are now placed on separate rows rather than on the same row

I'm relatively new to HTML, Jinja, and CSS and have been playing around with creating a webpage that retrieves data from a sqlite3 database. As of now, I am facing some challenges regarding formatting. To assist with table formatting and overall aest ...