Is it possible to subscribe to changes in an input type file using FormControl?

After subscribing to the FormControl.valueChanges() triggered by selecting a file on an input, I noticed that the value emitted does not include the full file path. Is there a way to access this information through subscription, or do we need to retrieve it directly from the element using @ViewChild? The HTML setup is as follows:

<input #file name='file' id='file' type='file' [formControl]='loadButton'/>

The subscription code looks like this:

this.loadButton.valueChanges
    .pipe(untilDestroyed(this))
    .subscribe(path => {
      console.dir(path);
    });
}

After selecting a file, the output in the console is:

C:\fakepath\test.png

Answer №1

For my latest project, I consolidated all the necessary functionality into a single component. Here's how I approached it:

import { Component, EventEmitter, Output } from '@angular/core';
@Component({
  selector: 'app-image-uploader',
  template: '<input type="file" (change)="onUploadFileChanged($event)" />',
})
export class ImageUploaderComponent implements OnInit {
    @Output() uploadStatusChange = new EventEmitter<any>();
    onUploadFileChanged(event) {
        this.targetElement = event.target;
        if (event.target.files && event.target.files[0]) {
            component.uploadStatusChange.emit('ready');
        }
    }

}

Once a file is selected, the component informs the parent component that it is ready, allowing you to then set the form control to true. The HTML structure of the parent component would look something like this, where in this example $event contains the string 'ready':

<app-image-uploader (uploadStatusChange)="yourFunction($event)"></app-image-uploader>

If dealing with images, you can also utilize FileReader to display them before uploading.

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

Invisible ReCaptcha by Google not living up to its invisible name

I am having trouble getting Google's Invisible ReCaptcha to function correctly after submitting a form. Despite setting my site-key for an invisible ReCaptcha, the "old" style ReCaptcha keeps appearing. I am unsure why this is happening and would appr ...

Customized AngularJS URLs

After gaining proficiency in BackboneJS and AMD, I have successfully completed multiple large projects. Now delving into AngularJS, I have already implemented it with AMD and created controllers and services with ease. The only challenge I'm facing i ...

ACE.js enhances website security through Content Security Policy

I've been working on setting up a helmet-csp with ace running smoothly. Here's how my helmet-setup looks: var csp = require("helmet-csp"); app.use(csp({ directives: { defaultSrc: ["'self'", "https://localhost:8000"], ...

Tips for assigning a Moment type to a class attribute in TypeScript

While I have no trouble using moment.JS and its methods, I'm currently facing an issue with setting the attribute in my class to be of type Moment, much like how we would set it as a type string or type boolean. For example: export class Event { c ...

Transforming complex nested JSON structures into simple flat JSON using TypeScript and RxJS operators such as map, reduce, and filter

Is there a way to convert the following structure into a simpler one without using complicated foreach loops? It would be great if this can be achieved with existing JS-Libraries like RxJS for Observables, Lodash/Underscore or any similar library. Here is ...

When attempting to utilize the Next.js Head component in a location other than _document, the page experiences

Currently, I am in the process of integrating Next.js with Typescript and Material UI. Despite the abundance of tutorials available online for setting up Next.js with Material UI, I have encountered a commonality among them where they all provide identical ...

Unusual problem with [(ngModel)] not updating after Apollo subscription

I've encountered a strange issue with [(ngModel)] while working on an Angular 5 project. I have set up a form with inputs that successfully connect to the database using Apollo for sending GraphQL queries and mutations. The issue arises in editing set ...

Transforming an object in TypeScript to another object while retaining the properties of the original type

Issue Struggling with TypeScript type casting here. Trying to convert an object of type B to type A, but without carrying over the properties from type B. Inquiry Is there a way to achieve this conversion without explicitly mentioning the otherName prop ...

Issue: The Auth Interceptor is expecting a stream but received 'undefined'. Please provide an Observable, Promise, Array, or Iterable instead

I am facing an issue where I need to intercept every request to api, check the status code, and display a message or redirect to a specific component. However, I keep encountering the following error: main.js:1580 TypeError: You provided 'undefined ...

Highcharts JS encountered an error: x[(intermediate value)(intermediate value)(intermediate value)] is not a valid constructor

I'm in the process of creating a bar chart by fetching options from an ajax response. However, I encountered an error when passing the object to the highcharts constructor. Uncaught TypeError: x[(intermediate value)(intermediate value)(intermediate v ...

The parameter type x cannot be assigned to the argument type '(x) => ObservableInput<{}>'

Looking for some insights on this issue Currently working with ngrx and attempting to utilize multiple switchMaps to call various action classes. Defined Actions: export class BlogAddedAction implements Action { readonly type = BLOG_ADDED_ACTION; ...

Reading JSON files in AngularJS is a common practice among developers

Creating a dynamic tree using JSON is a common task in AngularJS. To achieve this, you can store your JSON data in a separate file and then read it externally. Here's an example of how you can do this: Sample Controller Code: $scope.myjson = { ...

Executing code before a component mounts in ReactJs: What to do now that componentWillMount is no longer recommended?

Before my component mounts, I want to redirect the user to the home page based on a condition: componentWillMount(){ console.log("componentWillMount is called.") let userHasNotChosenOpportunity = true if (userHasNotChosenOpportunity) ...

What steps should I take to fix this TypeScript error?

I've been struggling to fix this error, but I'm unsure of the best way to resolve it. Here is the code snippet I've been working with:https://i.sstatic.net/m6M48.png Here is the specific error message: https://i.sstatic.net/uk6QY.png ...

Issue: Receiving an error message stating "Text data outside of root node" while attempting to install a

At times, I encounter an error when attempting to install any cordova plugin with Ionic (typically after 6pm GMT+0). These errors occur with plugins sourced from both npm and GitHub, and the message I receive is: Error: Text data outside of root node. Li ...

Guide to saving HTML form data into localstorage as a JSON string through JavaScript

What's the best way to retrieve form values for localStorage as a JSON string without using JQuery? I tried using a for loop but I'm having trouble.. any hints would be greatly appreciated (I'm still new at this). Thank you! <input type ...

Is there a way to create an event listener that responds to a simultaneous click of both mouse buttons?

Despite my extensive research on the Internet, I was unable to find any examples. Interestingly, Vue only supports right and left clicks separately which I find peculiar as it seems like a basic task that can easily be accomplished with plain Javascript. ...

Troubleshooting Problem with Custom Class Buttons in Angular Material

Recently, I've been working on creating a custom class for angular material buttons. However, I encountered an issue where the button fades out or turns white when I click on it and then navigate away from the browser window (minimize it or activate a ...

Is there a way to turn off grouping in the Angular Grid when there are no items to group?

Here is a snippet of code that includes an Angular component with an ag-Grid: @Component({ selector: 'my-app', template: `<ag-grid-angular style="height: 100%;" class="ag-theme-alpine" [columnDefs]=" ...

A Typescript Function for Generating Scalable and Unique Identifiers

How can a unique ID be generated to reduce the likelihood of overlap? for(let i = 0; i < <Arbitrary Limit>; i++) generateID(); There are several existing solutions, but they all seem like indirect ways to address this issue. Potential Solu ...