如何在 Angular2 反应形式中包含文件上传控件? [英] How to include a file upload control in an Angular2 reactive form?

查看:28
本文介绍了如何在 Angular2 反应形式中包含文件上传控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种奇怪的原因,没有在线教程或代码示例展示如何使用 Angular2 Reactive 表单,而不仅仅是简单的输入或选择下拉列表.

我需要创建一个表单来让用户选择他们的头像.(图片文件)

以下不起作用.(即 Avatar 属性从不显示任何值更改.)

profile.component.html:

 
<div class="row"><div class="col-md-4"><img src="{{imgUrl}}uploads/avatars/{{getUserAvatar}}" style="width:150px; height:150px;float:left;border-radius:50%;margin-right:25px;margin-left:10px;"><div class="form-group"><label>更新配置文件图片</label><input class="form-control" type="file" formControlName="avatar">

<div class="col-md-8"><div class="form-group"><标签 >名字:<input class="form-control" formControlName="firstname">

<div class="form-group"><标签 >姓氏:<input class="form-control" formControlName="lastname">

<div class="form-group"><标签 >电子邮件:<input class="form-control" formControlName="email">

<div class="form-group"><标签>密码:<input class="form-control" type="password" formControlName="password">

</表单><p>表单值:{{ profileForm.value |json }}</p><p>表单状态:{{ profileForm.status |json }}</p>

profile.component.ts:

import { Component, OnInit } from '@angular/core';从@angular/forms"导入 { FormBuilder, FormGroup, Validators };从'../../services/config.service'导入{配置};从../../services/auth.service"导入{AuthService};从'../../models/user.model'导入{用户};@成分({选择器:应用程序配置文件",templateUrl: './profile.component.html',styleUrls: ['./profile.component.css']})导出类 ProfileComponent 实现 OnInit {authUser:用户;profileForm : FormGroup;构造函数(私有 authService:AuthService,私有 fb:FormBuilder){}创建表单(){this.profileForm = this.fb.group({名字:[this.authUser.firstname, Validators.required ],姓氏:[this.authUser.lastname, Validators.required ],电子邮件:[this.authUser.email, Validators.required ],头像: [this.authUser.avatar, Validators.required ],密码:['xxxxxx', Validators.minLength(4)]});}ngOnInit() {this.authUser = this.authService.getAuthUser();this.createForm();} 

解决方案

可以在这里找到简单的答案.https://devblog.dymel.pl/2016/09/02/upload-file-image-angular2-aspnetcore/

HTML

 <button (click)="addFile()">添加</button>

组件.ts

@ViewChild("fileInput") fileInput;添加文件():无效{让 fi = this.fileInput.nativeElement;如果 (fi.files && fi.files[0]) {让 fileToUpload = fi.files[0];this.uploadService.upload(fileToUpload).subscribe(res => {控制台日志(res);});}}

service.ts

upload(fileToUpload: any) {让 input = new FormData();input.append("file", fileToUpload);return this.http.post("/api/uploadFile", input);}

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:

               <form [formGroup]="profileForm" novalidate>
                 
                        <div class="row">
                            <div class="col-md-4 ">
                                <img src="{{imgUrl}}uploads/avatars/{{getUserAvatar}}" style="width:150px; height:150px;float:left;border-radius:50%;margin-right:25px;margin-left:10px;">

                                <div class="form-group">
                                    <label>Update Profile Image</label>
                                    <input class="form-control" type="file" formControlName="avatar">
                                </div>
                            </div>
                            <div class="col-md-8 ">
                                <div class="form-group">
                                    <label >Firstname:
                                        <input class="form-control" formControlName="firstname">
                                    </label>
                                </div>
                                <div class="form-group">
                                    <label >Lastname:
                                        <input class="form-control" formControlName="lastname">
                                    </label>
                                </div>
                                <div class="form-group">
                                    <label >Email:
                                        <input class="form-control" formControlName="email">
                                    </label>
                                </div>
                                <div class="form-group">
                                    <label >Password:
                                        <input class="form-control" type="password" formControlName="password">
                                    </label>
                                </div>
                            </div>
                        </div>
                 
                </form>
                <p>Form value: {{ profileForm.value | json }}</p>
                <p>Form status: {{ profileForm.status | json }}</p>

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

解决方案

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

这篇关于如何在 Angular2 反应形式中包含文件上传控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆