file-upload-with-preview angular 9 code example
Example 1: preview image in angular 8
<form [formGroup]="uploadForm" (ngSubmit)="submit()">
<!-- Select File -->
<input type="file" accept="image/*" (change)="showPreview($event)" />
<!-- Image Preview -->
<div class="imagePreview" *ngIf="imageURL && imageURL !== ''">
<img [src]="imageURL" [alt]="uploadForm.value.name">
</div>
<!-- Assign Image Alt -->
<input formControlName="name" placeholder="Enter name">
<button type="submit">Submit</button>
</form>
Example 2: preview image in angular 8
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from "@angular/forms";
@Component({
selector: 'app-file-upload',
templateUrl: './file-upload.component.html',
styleUrls: ['./file-upload.component.css']
})
export class FileUploadComponent implements OnInit {
imageURL: string;
uploadForm: FormGroup;
constructor(public fb: FormBuilder) {
this.uploadForm = this.fb.group({
avatar: [null],
name: ['']
})
}
ngOnInit(): void { }
showPreview(event) {
const file = (event.target as HTMLInputElement).files[0];
this.uploadForm.patchValue({
avatar: file
});
this.uploadForm.get('avatar').updateValueAndValidity()
const reader = new FileReader();
reader.onload = () => {
this.imageURL = reader.result as string;
}
reader.readAsDataURL(file)
}
submit() {
console.log(this.uploadForm.value)
}
}