奇妙なことに、Angular2 Reactiveフォームを単純な入力や選択ドロップダウン以外で使用する方法を示すチュートリアルやコードサンプルは、オンラインにはありません。
ユーザーが自分のアバターを選択できるフォームを作りたいのですが、どうすればいいですか?(画像ファイル)
以下はうまくいきません‼。(すなわち、Avatar プロパティは値の変更を決して示しません。)
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();
}
シンプルな答えは、ここにあります。 https://devblog.dymel.pl/2016/09/02/upload-file-image-angular2-aspnetcore/
HTML
<input #fileInput type="file"/>
<button (click)="addFile()">Add</button>
コンポーネント.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);
});
}
}
サービス.ts
upload(fileToUpload: any) {
let input = new FormData();
input.append("file", fileToUpload);
return this.http.post("/api/uploadFile", input);
}
私は少し遅れていますが、同じ解決策を探している他の人のために、ここに来るかもしれません。 これは私の ファイル入力アクセサで、Reactiveまたはテンプレート駆動のフォームで使用できます。デモはこちら。
画像サイズやファイルサイズ、拡張子、種類をチェックするために使用できるオプションのバリデーションが用意されていますが、これはデフォルトでは無効になっています。
npm i file-input-accessor` を実行して、AppModule の import にモジュールを追加します。
import {BrowserModule} from '@angular/platform-browser';
import {FileInputAccessorModule} from "file-input-accessor";
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FileInputAccessorModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
そして、他の入力と同じようにファイル入力を使用します。
<!--Reactive Forms-->
<input type="file" multiple [formControl]="someFileControl" />
<input type="file" multiple formControlName="someFileControl" />
<!--Template-driven-->
<input type="file" name="file-input" multiple [(ngModel)]="fileList" />
他のリアクティブコントロールと同様に、valueChanges プロパティを購読することができます。
以下の方法で、あらゆるタイプのフォームに画像をアップロードすることができます。
コントロールに1つの変更メソッドを公開します。
<input class="form-control" type="file" name="avatar" (change)="imageUpload($event)">
<img [src]="imageUrl" />
クラス内に以下のロジックを追加します。
// Declare the variable.
imageUrl: any;
//method definition in your class
imageUpload(e) {
let reader = new FileReader();
//get the selected file from event
let file = e.target.files[0];
reader.onloadend = () => {
//Assign the result to variable for setting the src of image element
this.imageUrl = reader.result;
}
reader.readAsDataURL(file);
}
}
画像がアップロードされたら、フォームモデルを更新するために this.imageUrl を使用することができます。 画像やファイルをサーバーにアップロードするには、以下のリンクを参照してください。
https://stackoverflow.com/questions/35985347/how-to-upload-file-in-angular2?rq=1
この解決策がうまくいっているかどうか教えてください。