如何使用角度6中的Reactive表单通过另一个FormControl发送FormData?

时间:2018-09-05 14:26:49

标签: angular6 angular-reactive-forms

我使用角度6的反应形式制作了一个包含电子邮件用户名和头像等字段的表单。我知道我需要表格数据来上传图像,但是我不知道如何将其与角度6的反应形式一起使用。帮助吗?

1 个答案:

答案 0 :(得分:4)

尝试一下:

     <form [formGroup]="yourForm" (ngSubmit)="onSubmit()">
       <input type="text" formControlName="email"> <br>
       <input (change)="uploadDocument($event)" type="file" accept=".png, .pdf, .jpg, .jpeg"> <br>
       <input (change)="onSubmit()" type="submit" value="Send file">
     </form>  

在您的app.component.html中,然后:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  yourForm: FormGroup;

  constructor(private fb: FormBuilder, private http: HttpClient) {
    this.yourForm = this.fb.group({
      email: [''],
      file: ['']
    });
  }

  uploadDocument(event: any) {
    if (event.target.files && event.target.files[0]) {
      const reader = new FileReader();
      reader.onload = () => {
        this.yourForm.get('file').setValue(event.target.files[0]);
      };
      reader.readAsDataURL(event.target.files[0]);
    }
  }

  onSubmit(): void {
    const uploadData = new FormData();
    uploadData.append('email', this.yourForm.get('email').value);
    uploadData.append('file', this.yourForm.get('file').value);
    this.http.post('your-route', uploadData);
  }
}

在您的app.component.ts中,并且:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [AppComponent, HelloComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }
您的app.module.ts文件中的

。 另外,请不要忘记在this.http.post('your-route', uploadData);行中配置路由。