javascriptangulartypescriptrxjshtml5-filesystem

Subscribing to input type file changes with FormControl?


When I subscribe to a FormControl.valueChanges() that is triggered by the selection of a file on an input the value emitted does not contain the full path to the file that was selected. Is it possible to obtain this information via subscription or do we have to pull it off of the element directly with @ViewChild to get direct access to the element? The setup looks like this:

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

It's subscribed to like this:

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

When a file is selected the logged statement looks like this:

C:\fakepath\test.png

Solution

  • In my project, I did it in one component, like:

    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');
            }
        }
    
    }
    

    Now, after selected file, the component will told parent component I'm ready, then you can set fromControl patch it to true. The HTML of parent component like, for above exmaple, the $event equal string 'ready':

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

    For image, you also can use FileReader show it before upload.