Tips for storing an image in local storage with an angular reactive form

I'm currently working on an Angular project where my goal is to implement a feature that allows users to upload an image using an angular reactive form and then store that image in the local storage.

Here is a snippet of the code from "edit.component.html" file:

<form [formGroup]="form" (ngSubmit)="save()">
<label class="head1">Photo</label> <br>
<input type="file" formControlName="Photo">
<button [disabled]="form.invalid">Save</button>
</form>

And here is a glimpse of the code inside "edit.component.ts":

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormArray} from '@angular/forms';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent {
form=new FormGroup({
    Photo:new FormControl(null,Validators.required),
});
save(){
    var profile;

    if(localStorage.getItem("profile")==null){
      profile={};
    }
    else{
      profile=JSON.parse(localStorage.getItem("profile")!);
    }

    // Need help with saving the image to localstorage
}
}

Upon adding the line

const photo = this.form.get('Photo') as File;
in the save() function of ts file, I encountered the following error:

Conversion of type 'AbstractControl<null, null> | null' to type 'File' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  Type 'AbstractControl<null, null>' is missing the following properties from type 'File': lastModified, name, webkitRelativePath, size, and 6 more.ts(2352)

Could someone please offer guidance or suggest modifications to successfully save the image in localstorage and display it on the HTML page?

Answer №1

To convert an image into a string, you can use the FileReader method as local storage works with strings. You can then save this converted string.

Afterwards, you have the option to retrieve the string from local storage and convert it back into a file using the File method, adding it back to the form.

You can set up a listener for changes in the file field, which will capture the file, assign it to the form, and save it accordingly.

If you'd like to see a demonstration of this process, check out this Stackblitz example.

Feel free to customize these methods based on your specific requirements.

Key methods:

File Handler:

<input
    type="file"
    formControlName="Photo"
    (change)="handleFileInput($event)"
  />
handleFileInput(event: Event) {
    const target = event.target as HTMLInputElement;

    const files = target.files as FileList;

    const file = files[0];

    this.form.value.Photo = file;

    this.saveFile(file);
}

Save File:

saveFile(file: File) {
    const reader = new FileReader();

    reader.onloadend = () => {
      console.log(reader.result);

      this.preview = reader.result as string;

      localStorage.setItem('profile', reader.result as string);
    };
    reader.readAsDataURL(file);
}

Read File:

readFile() {
    const profile = localStorage.getItem('profile');

    console.log('reading ls image: ', profile);

    if (profile) {
      this.preview = profile;

      const contentType = profile.split(';')[0].replace('data:', '');

      const file = new File([profile], 'profile.jpeg', {
        type: contentType,
      });

      this.form.value.Photo = file;
    } else {
      this.preview = '';
    }
}

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

Enable Angular Server-Side Rendering for seamless navigation without refreshing the page when clicking

Can Angular SSR be utilized to navigate between pages without requiring a reload? ...

Is it best practice to utilize multiple Angular routing files?

Currently, I am working on a personal project to enhance my learning experience. Today, I encountered a question while expanding my codebase by creating additional modules. My goal is to prevent app.module from becoming overwhelmed with component imports, ...

Assign variable data to properties within an immutable object within a React component

I have declared a Const in my config.service.ts file like this: export const mysettings={ userid:"12324", conf:{ sessionDuration:30, mac:"LON124" } } I am using this constant in various components. However, instead of hardcoding these val ...

Resetting Laravel passwords without relying on user emails, with the additional use of Angular for the front end interface

I'm currently working on a laravel-angular application that requires a password reset feature. However, the default password-reset in Laravel relies on email verification, which is not necessary for this particular application. I tried setting $confir ...

The issue arises when attempting to invoke a method from a global mixin in a Vue3 TypeScript component

I've been working on this challenge for the past week, and I would appreciate any help or insights from those who may have experience in this area. Currently, I am in the process of converting vue2-based code to vue3 for a new project. Instead of usi ...

Transform a list of time slots into a time interval using Angular (2/4/5/6)

Hello everyone! Just wanted to share my updated solution after considering your feedback. Thank you! getTime(apptTime) { const fields = apptTime.split("-"); const startingTime = this.formatTime(+fields[0]); const endingTime = this.formatTime(+fie ...

Unit testing Angular2 by simulating HttpResponse

I encountered a challenge in one of my unit tests where I needed to mock an HTTP response. Despite following the correct procedures, I kept receiving the error below: ‘TypeError: Cannot read property 'subscribe' of undefined’ The issue stem ...

Leveraging Java and TypeScript code for specific functionalities within an Ionic 2 Android application

When it comes to creating hybrid apps that support Windows, iOS, and Android simultaneously using web technologies such as Html, CSS, and Js, Ionic is the go-to choice. However, there may be certain features not supported by the Ionic 2 framework. Is it ...

Is it considered valid in JavaScript or TypeScript to group values using (value1 || value2) for comparisons, and if it is, what is the reasoning behind

Does anyone know if using the || operator to group values while comparing a single variable is valid in the most recent versions of JavaScript or TypeScript? If not, what could be preventing this from becoming a valid syntactic sugar feature at some point? ...

Exception occurs when arrow function is replaced with an anonymous function

Currently, I am experimenting with the Angular Heroes Tutorial using Typescript. The code snippet below is functioning correctly while testing out the services: getHeroes() { this.heroService.getHeroes().then(heroes => this.heroes = heroes); } H ...

Validation Form Controls

Here is a piece of code that works for me: this.BridgeForm = this.formBuilder.group({ gateway: ["", [Validators.required, Validators.pattern(this.ipRegex)]], }); However, I would like to provide more detail about the properties: this.BridgeF ...

ngClass is failing to be implemented

Does anyone know how to dynamically apply a CSS style to an input based on a variable value? HTML <input class="defaultInput" [ngClass]="{'inputerror':'emptyFields'}" formControlName="idAnnuaire" placeholder="Ex: c20011"> CSS ...

Verify if an entity (either an object or a class) possesses a specific attribute

Imagine having a class like this: module MyModule { export class MyClass { x:number; y:number; } } Now, let's say we have a string called "x". How can we determine if MyClass has the property "x"? If an instance of MyClass is ...

A guide on retrieving bytecode from a specific PDF using Angular

Can anyone help me with extracting the bytecode from a selected PDF file to save it in my database? I keep encountering an error stating that my byte is undefined. Could someone please review my code and identify what might be causing this issue? I attemp ...

What's the best way to refactor the `await nextEvent(element, 'mousemove')` pattern in my code once it is no longer necessary?

Within my React component, the code includes the following: class MyComponent extends React.Component { // ... trackStats = false componentDidMount() { this.monitorActivity() } componentWillUnmount() { this.trackStat ...

I am interested in incorporating a personalized class into the Kendo UI for Angular TabStrip

<kendo-tabstrip (tabSelect)="onTabSelect($event)"> <kendo-tabstrip-tab title="Paris" [selected]="true"> <ng-template kendoTabContent> <div class="content"> ...

When running `ng build --prod`, an error is thrown indicating that the module does not have

Whenever I try to build in Azure, I encounter an error. However, locally the command 'ng build --prod' works perfectly fine. Error: Module [path_to_file] has no static exports true Since this is for production purposes, I am hesitant to use t ...

Tips for incorporating JSON in server-side rendering using Angular Universal

Currently, I am in the process of developing an angular2-universal app for a university project which is also my bachelor thesis. My goal is to have this app rendered on the server using angular universal. However, I am facing a challenge in loading my .js ...

Is there any drawback in transforming Observables into promises?

There are situations where subscribing in a component is necessary instead of using an async pipe. In scenarios where only one value will be emitted by the observable, is there any drawback or downside to converting it to a promise? If we are not subscrib ...

Angular 2 Checkbox Filtering: Simplifying Your Data Selection

Presented are a series of tasks in the form of objects within a table, accompanied by two checkboxes: "Night" and "Day". The desired scenario involves filtering the tasks based on the checkbox selections. If the "Night" checkbox is checked, only tasks wit ...