1<form [formGroup]="uploadForm" (ngSubmit)="submit()">
2 <!-- Select File -->
3 <input type="file" accept="image/*" (change)="showPreview($event)" />
4
5 <!-- Image Preview -->
6 <div class="imagePreview" *ngIf="imageURL && imageURL !== ''">
7 <img [src]="imageURL" [alt]="uploadForm.value.name">
8 </div>
9
10 <!-- Assign Image Alt -->
11 <input formControlName="name" placeholder="Enter name">
12
13 <button type="submit">Submit</button>
14</form>
1import { Component, OnInit } from '@angular/core';
2import { FormBuilder, FormGroup } from "@angular/forms";
3
4@Component({
5 selector: 'app-file-upload',
6 templateUrl: './file-upload.component.html',
7 styleUrls: ['./file-upload.component.css']
8})
9
10export class FileUploadComponent implements OnInit {
11 imageURL: string;
12 uploadForm: FormGroup;
13
14 constructor(public fb: FormBuilder) {
15 // Reactive Form
16 this.uploadForm = this.fb.group({
17 avatar: [null],
18 name: ['']
19 })
20 }
21
22 ngOnInit(): void { }
23
24
25 // Image Preview
26 showPreview(event) {
27 const file = (event.target as HTMLInputElement).files[0];
28 this.uploadForm.patchValue({
29 avatar: file
30 });
31 this.uploadForm.get('avatar').updateValueAndValidity()
32
33 // File Preview
34 const reader = new FileReader();
35 reader.onload = () => {
36 this.imageURL = reader.result as string;
37 }
38 reader.readAsDataURL(file)
39 }
40
41 // Submit Form
42 submit() {
43 console.log(this.uploadForm.value)
44 }
45
46}