How to include a file upload control in an Angular2 reactive form?

Tuthmosis picture Tuthmosis · Apr 17, 2017 · Viewed 44.3k times · Source

For some weird reason, there are just no tutorials or code samples online showing how to use Angular2 Reactive forms with anything more than simple input or select dropdowns.

I need to create a form to let users select their avatar. (Image file)

The following doesn't work. (i.e. The Avatar property never shows any value changes.)

profile.component.html:

profile.component.ts:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup,  Validators } from '@angular/forms';
import {Config} from '../../services/config.service';
import {AuthService} from '../../services/auth.service';
import {User} from '../../models/user.model';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
  
  authUser:User;

  profileForm : FormGroup; 

  constructor(private authService:AuthService, private fb: FormBuilder) {}
          
  createForm() {
    this.profileForm = this.fb.group({
      firstname:  [this.authUser.firstname, Validators.required ],
      lastname: [this.authUser.lastname, Validators.required ],
      email: [this.authUser.email, Validators.required ],
      avatar: [this.authUser.avatar, Validators.required ],
      password:['xxxxxx', Validators.minLength(4)] 
    });
  }
  ngOnInit() {
    this.authUser = this.authService.getAuthUser();

    this.createForm();
  } 

Answer

Tuthmosis picture Tuthmosis · Apr 18, 2017

Simple answer can be found here. https://devblog.dymel.pl/2016/09/02/upload-file-image-angular2-aspnetcore/

The HTML

    <input #fileInput type="file"/>
    <button (click)="addFile()">Add</button>

Component.ts

@ViewChild("fileInput") fileInput;

addFile(): void {
let fi = this.fileInput.nativeElement;
if (fi.files && fi.files[0]) {
    let fileToUpload = fi.files[0];
    this.uploadService
        .upload(fileToUpload)
        .subscribe(res => {
            console.log(res);
        });
    }
}

The service.ts

upload(fileToUpload: any) {
    let input = new FormData();
    input.append("file", fileToUpload);

    return this.http.post("/api/uploadFile", input);
}