Assign a value to a file input in Angular 6

I'm currently working with Angular 6 and I have a requirement to retrieve an image that is dropped into a div element and assign it as the value of an input type="file" within a form.

The process involves the user dropping an image into the designated div, which should then be captured by the file input, allowing for form submission.

Below is the code snippet:

<form [formGroup]="imageUpload" (ngSubmit)="imageUploadSubmitted()">
  <div id="imageDrop" (drop)="drop($event)" (dragover)="allowDrop($event)" #imageDrop></div> 

  <input type="file" formControlName="imageInput" required #imageInput id="imageInput"  >
  <label>
    <input type="text" formControlName="imageName" placeholder="name" required >
  </label>                      

  <button type="submit" [disabled]="!imageUpload.valid">Submit</button>
</form>

In addition, there is the corresponding component:

  allowDrop(e) {
    e.preventDefault();
  }

  drop(e) {
    e.preventDefault();  
    this.imageUpload.controls.imageInput.reset();  
    this.imageDrop.innerHTML="";    
    let input = this.imageUpload.controls.imageInput as any;
    input.value = e.dataTransfer.files[0];  
    this.readfiles(e.dataTransfer.files);
  }

  readfiles(files){
    const reader = new FileReader();
    let image = new Image();
    reader.onload =  (event) => {
      this.imageDrop.nativeElement.innerHTML="";                
      let fileReader = event.target as FileReader;
      image.src = fileReader.result;
      image.width = 150; 
      this.imageDrop.nativeElement.appendChild(image);  
      /*if (this.imageUpload.controls.imageInput.value==null) {                
        let input = this.imageUpload.controls.imageInput as any;        
        input.value = event.target.result;  
      }  */
    };
    reader.readAsDataURL(files[0]);    

  }

Despite having a value in the input.value upon dropping, it seems to be of the incorrect type, rendering the submit button inactive.

To address this issue, consider moving the logic from the readfiles function. The proposed code changes do not work due to an error related to result. The specific error message is

Property result does not exist on type EventTarget
.

If you have insights on how I can resolve this and successfully set the image as the value of the file input, please share your suggestions.

Thank you for your assistance.

P.S. Here is the StackBlitz link

Answer №1

What specific value are you looking to retrieve from the imageInput formControl?

To ensure that it functions correctly, consider updating the input.value to:

input.setValue(e.dataTransfer.files[0]);

By doing this, the formControl will be accurately maintained and no longer marked as INVALID. However, if you encounter issues due to using an input file, which expects a fileName, you can modify the HTML by removing type="file" to allow your form to operate smoothly ;)


If you're interested, here is my own image chooser tool that supports ngModel or formControlName and allows for initialization with base 64: https://github.com/xrobert35/asi-ngtools/tree/angular6-compatibility/src/components/asi-image-chooser You can also access a live 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

Parsing error encountered while trying to handle an unexpected token at line 214, character 33. It appears that an appropriate loader is missing to process this particular file type

I've been developing a Typescript React project for the past few months without any issues. However, things took a turn yesterday when I decided to run npm audit fix and npm audit fix --force in order to address some security concerns that appeared ou ...

Error with the type of CanvasGradient in the NPM package for converting text to image

I attempted to generate an image using a specific text by utilizing npm's text-to-image package, but encountered an error during typescript compilation. The errors I encountered upon running the typescript compilation command are related to files with ...

Changing the color of the pre-selected date in the mat-datepicker Angular component is a key feature that can enhance the

Is there a way to adjust the color of the preselected "today" button in mat-datepicker? https://i.stack.imgur.com/wQ7kO.png ...

problem with arranging sequences in angular highcharts

I am facing an issue with sorting points in different series using highcharts. To illustrate my problem, consider the following example series: [ {name: 'series one', value: 5 values}, {name: 'series two', value: 10 values} ] When usin ...

Adding SVG to Component

I am attempting to embed an SVG element (retrieved using http.get()) into a 'icon' component. export class BgIcon { private svgSrc_: string; icon_: Icon; @Input('svg-src') set svgSrc(value: string) { this.svgSrc_ = value; ...

What is the process for updating button text upon clicking in Angular?

To toggle the text based on whether this.isDisabled is set to false or true, you can implement a function that changes it when the button is clicked. I attempted to use this.btn.value, but encountered an error. import { Component } from '@angular/core ...

Understanding 'this' in ChartJS within an Angular application

Here is my event handler for chartJS in Angular that I created: legend: { onClick: this.toggleLegendClickHandler After changing the text of the y scale title, I need to update the chart. I am looking to accomplish this by calling this._chart.cha ...

Encountered an issue in React Native/Typescript where the module 'react-native' does not export the member 'Pressable'.ts(2305)

I have been struggling to get rid of this persistent error message and I'm not sure where it originates from. Pressable is functioning correctly, but for some reason, there is something in my code that doesn't recognize that. How can I identify t ...

Tips for accessing HttpParams within a WebApi Controller while utilizing the [HttpPut] method

I am attempting to update a specific resource by accessing it through the PUT method in an Angular service. RollBackBatchById(selectedBatchId: number) { const params = new HttpParams(); params.append('resourceId', resourceId.toString()); ...

A guide on converting JSON to TypeScript objects while including calculated properties

I have a standard JSON service that returns data in a specific format. An example of the returned body looks like this: [{ x: 3, y: 5 }] I am looking to convert this data into instances of a customized TypeScript class called CustomClass: export class ...

Redirecting with Angular2 from a static function

Hello, I currently have a 'static class' called Utils which contains only static methods (helpers): export class Utils { static doSomethingAndRedirect() { ...do something... redirectTo->'/home' } } I am ...

What is preventing typescript from inferring these linked types automatically?

Consider the following code snippet: const foo = (flag: boolean) => { if (flag) { return { success: true, data: { name: "John", age: 40 } } } return { success: false, data: null } ...

Why aren't the child route components in Angular 6 loading properly?

I have encountered a small problem. I developed an app using Angular 6 with children routes implemented like this: { path:'pages', component:DatePagesComponent, children : [ {path:'404', component:Error404C ...

Experiencing a challenge while attempting to integrate AWS Textract with Angular using the aws-sdk/client-textract npm package. Despite my efforts, I keep encountering a Credentialerror

I have set up aws-sdk/client-textract in my app.component.ts file and specified the region for my Textract service. However, I am unsure of where to provide my access_key and secret_key, as well as what parameters need to be passed for Textract. If anyone ...

Tips for finding your way to a destination with specific parameters

I'm currently viewing the following route: http://localhost:4200/#/corp/projects/detail/05940c57/page1 Now I need to access http://localhost:4200/#/corp/projects/detail/05940c57/page2 Is it possible to switch to "page2" using navigate() or navigat ...

What steps should I follow to implement Cypress in an older project?

Looking to automate a project built with Node.js version 8.9.4 and an older version of Angular using Cypress for testing, but running into compatibility issues with the current version of Cypress. Is there a way to use an older version of Cypress in this ...

PrismaClient is currently incompatible with this browser environment and has been optimized for use in an unknown browser when performing updates

While attempting to update a single field in my database using server-actions and tanstackQuery, I encountered the following error message: Error: PrismaClient is unable to run in this browser environment, or has been bundled for the browser (running in ...

Angular2 app is sending empty HTTP headers to the server

My REST api, built using SpringBoot, incorporates JWT for authentication and authorization. To achieve this, I utilize a FilterRegistrationBean. Within this setup, there exists a class called JwtFilter that extends GenericFilterBean. This class is respons ...

Utilizing nested namespaces for optimal organization and clarity

Is it possible to export a namespace A with another namespace B nested within it? For example: // b.ts export namespace B { export const val = 'val'; } // a.ts export namespace A { //... some thing import B as namespace } --- the above wil ...

Create a fresh array by merging two existing arrays together

My project involves working with two separate arrays. The first array contains normal date values: var = [ "2022-05-01", "2022-05-02", ... "2022-05-30" ] The second array consists of objects that contain s ...