Skip to content

Instantly share code, notes, and snippets.

@merlosy
Last active May 22, 2021 22:13
Show Gist options
  • Save merlosy/ab33dd7edaacfd92d6c9a5daea0a1240 to your computer and use it in GitHub Desktop.
Save merlosy/ab33dd7edaacfd92d6c9a5daea0a1240 to your computer and use it in GitHub Desktop.
Angular 4+ Material input field

Angular Material - File Upload field

  • Compatible with model driven validation (Reactive forms)
  • tested on Angular Material Beta 12
  • Implemented with Angular 4.4.x

For easier maintaining, I moved all sources on Plunker: SEE LIVE DEMO ON PLUNKER

Note: Getting the model value, returns an FileInput object (type FileInput)

@GoLucas
Copy link

GoLucas commented Feb 21, 2018

Hey, could you write here a simple example ?

@rvalenciano
Copy link

rvalenciano commented Mar 14, 2018

Hey @GoLucas I managed to send the @merlosy solution to the backend. In your service, before doing the post:

  submitReport(context: ReportContext): Observable<Response> {
    const httpOptions = {
      headers: new HttpHeaders({
        'Authorization': this.authenticationService.credentials.token
      })
    };

    let fileList = context.file.files;
    if (fileList.length > 0) {
      let file: File = fileList[0];
      let formData:FormData = new FormData();
      formData.append('name', context.name);
      formData.append('file', file, file.name);
      return this.httpClient
      .post(someURL, formData, httpOptions) 
      .pipe(
        map((body: any) => {
          console.log(body);
          const response = {statusCode: 200, message: 'Form submitted correctly'};
          return response;
        })
      );
    } else {
      // raise exception
    }
  }

and where context.file.files came from an interface defined before the service:

 export interface ReportContext {
   name: string;
   file: string|any;
  }

@merlosy
Copy link
Author

merlosy commented May 22, 2018

UPDATE: use the recommended library right now!
https://github.com/merlosy/ngx-material-file-input

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment