Tuesday, 2 October 2018

Upload Image in angular 4 Single image



import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";

@Component({
selector: 'app-image-upload',
templateUrl: './image-upload.component.html',
styleUrls: ['./image-upload.component.css']
})
export class ImageUploadComponent implements OnInit {

form: FormGroup;
loading: boolean = false;

@ViewChild('fileInput') fileInput: ElementRef;
ngOnInit() {
}
constructor(private fb: FormBuilder) {
this.createForm();
}
createForm() {
this.form = this.fb.group({
name: ['', Validators.required],
avatar: null
});
}

onFileChange(event) {
let reader = new FileReader();
if (event.target.files && event.target.files.length > 0) {
let file = event.target.files[0];
reader.readAsDataURL(file);
reader.onload = () => {
this.form.get('avatar').setValue({
filename: file.name,
filetype: file.type,
// value: reader.result.split(',')[1]
value: reader.result
})
};
}
}

onSubmit() {
const formModel = this.form.value;
this.loading = true;
// In a real-world app you'd have a http request / service call here like
// this.http.post('apiUrl', formModel)
setTimeout(() => {
console.log(formModel);
alert('done!');
this.loading = false;
}, 1000);
}

clearFile() {
this.form.get('avatar').setValue(null);
this.fileInput.nativeElement.value = '';
}
}


<p>
image-upload works!
</p>
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Bob" formControlName="name">
</div>
<div class="form-group">
<label for="avatar">Avatar</label>
<input type="file" id="avatar" (change)="onFileChange($event)" #fileInput>
<button type="button" class="btn btn-sm btn-default" (click)="clearFile()">clear file</button>
</div>

<button type="submit" [disabled]="form.invalid || loading" class="btn btn-success">Submit <i class="fa fa-spinner fa-spin fa-fw" *ngIf="loading"></i></button>
</form>







No comments:

Post a Comment

IIS deployment support details

  Node JS - IIS deployment support details node: http://go.microsoft.com/?linkid=9784334 IISNode: https://github.com/azure/iisnode/releases/...