Wednesday, October 30, 2019

How to upload image with Reactive Forms in Angular 7|8

Step1. Create project 
ng new DemoUpload
Step 2: import code css in file style.css
/* Add application styles & imports to this file! */
@import url('https://fonts.googleapis.com/css?family=Muli:200,300,400,600');
body {
  font-family: 'Muli', sans-serif;
  background: #F5F5F6;
}
.jumbotron {
  padding: 20px 2rem 27px;
  background: #312BC6;
  margin: 0 auto 25px;
  border-radius: 0;
}
.h1,
h1 {
  font-size: 25px;
  color: #4EABE6;
  font-weight: 300;
  margin: 0;
}
h5 {
  font-weight: 600;
}
.custom-wrapper {
  max-width: 460px;
  margin: 0 auto 150px;
}
.h2,
h2 {
  font-size: 1.45rem;
}
label {
  font-size: 15px;
  font-weight: 600;
  color: #222;
  margin-bottom: 6px;
}
.group-gap {
  margin-bottom: 40px;
}
.btn.focus,
.btn:focus,
.form-control:focus,
.custom-select:focus,
.custom-select:focus {
  box-shadow: none;
}
.form-control:focus,
.custom-select:focus {
  border: 1px solid #0C1CFF;
}
.btn-success,
.btn-success:hover {
  color: #312BC6;
  border-color: #00FC79;
  background-color: #00FC79;
}
.btn-group-lg>.btn,
.btn-lg {
  padding: 13px 15px 15px;
  font-size: 16px;
  border-radius: 0;
  text-transform: uppercase;
}
.btn-group-sm>.btn,
.btn-sm {
  padding: 10px 16px 10px;
  font-size: 15px;
  line-height: 1.5;
  border-radius: 0;
}
.avatar-upload {
  position: relative;
  max-width: 205px;
  margin: 10px auto 30px;
}
.avatar-upload .avatar-edit {
  position: absolute;
  right: 19px;
  z-index: 1;
  top: 13px;
}
.avatar-upload .avatar-edit input {
  display: none;
}
.avatar-upload .avatar-edit .custom-label {
  display: inline-block;
  width: 34px;
  height: 34px;
  margin-bottom: 0;
  border-radius: 100%;
  background: #3efc78;
  border: 1px solid transparent;
  box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.25);
  cursor: pointer;
  font-weight: normal;
  transition: all 0.2s ease-in-out;
}
.avatar-upload .avatar-edit .upload-image {
  background: #3efc78;
}
.avatar-upload .avatar-edit .remove-image {
  background: #E91E63;
}
.avatar-upload .avatar-edit .custom-label:hover {
  opacity: 1;
}
.avatar-upload .avatar-edit .custom-label:after {
  position: absolute;
  text-align: center;
  margin: auto;
  top: 8px;
  right: 0;
  left: 2px;
  width: 18px;
}
.avatar-upload .avatar-edit .upload-image:after {
  content: url('/assets/edit.svg');
}
.avatar-upload .avatar-edit .remove-image:after {
  content: url('/assets/close.svg');
  left: 0px !important;
}
.avatar-upload .avatar-preview {
  width: 200px;
  height: 200px;
  position: relative;
  border-radius: 100%;
  overflow: hidden;
  border: 12px solid #fff;
  -webkit-box-shadow: 0 0 45px rgba(0, 0, 0, .2);
  -moz-box-shadow: 0 0 45px rgba(0, 0, 0, .2);
  box-shadow: 0 0 45px rgba(0, 0, 0, .2);
}
.avatar-upload .avatar-preview>div {
  width: 100%;
  height: 100%;
  border-radius: 100%;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}
.form-control {
  height: auto;
  padding: 15px;
  font-size: 14px;
  color: #222222;
  border-radius: 0;
  background: #FDFDFD;
  border: 1px solid #312BC6;
}
.custom-select {
  height: auto;
  padding: 15px;
  font-size: 14px;
  cursor: pointer;
  font-weight: 400;
  color: #222222;
  background-color: #FDFDFD;
  border: 1px solid #312BC6;
}
.custom-control-input:checked~.custom-control-label::before {
  border-color: #E91E63;
  background-color: #E91E63;
}
.custom-control-input:focus~.custom-control-label::before {
  box-shadow: none;
}
.custom-control-label {
  cursor: pointer;
}
.error:focus,
.error {
  border-color: #E91E63;
  color: #E91E63;
}
.invalid-feedback {
  color: #E91E63;
}
.btn-danger,
body .btn-danger:hover {
  background: #E91E63;
  border-color: #E91E63;
  color: white;
}
.subjectList {
  margin: 0;
  padding: 0;
  list-style: none;
}
.subjectList li {
  display: block;
  width: 100%;
  margin-bottom: 10px;
}
.invalid-feedback {
  display: block;
}
.mb-3,
.my-3 {
  margin-bottom: 15px !important;
}
.custom-control {
  margin-bottom: 5px;
}
.custom-control label {
  font-weight: 400;
}
Step 3: insert in file index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>AngularReactiveForms</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>

Step 4: code in AppComponent component
import { Component, ChangeDetectorRef, ElementRef, ViewChild } from '@angular/core';
import { FormBuilder, FormArray, Validators } from "@angular/forms";
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 
  constructor(
    public fb: FormBuilder,
    private cd: ChangeDetectorRef
  ) {}
  /*##################### Registration Form #####################*/
  registrationForm = this.fb.group({
    file: [null]
  }) 
  /*########################## File Upload ########################*/
  @ViewChild('fileInput') el: ElementRef;
  imageUrl: any = 'https://i.pinimg.com/236x/d6/27/d9/d627d9cda385317de4812a4f7bd922e9--man--iron-man.jpg';
  editFile: boolean = true;
  removeUpload: boolean = false;
  uploadFile(event) {
    let reader = new FileReader(); // HTML5 FileReader API
    let file = event.target.files[0];
    if (event.target.files && event.target.files[0]) {
      reader.readAsDataURL(file);
      // When file uploads set it to file formcontrol
      reader.onload = () => {
        this.imageUrl = reader.result;
        this.registrationForm.patchValue({
          file: reader.result
        });
        this.editFile = false;
        this.removeUpload = true;
      }
      // ChangeDetectorRef since file is loading outside the zone
      this.cd.markForCheck();       
    }
  }
  // Function to remove uploaded file
  removeUploadedFile() {
    let newFileList = Array.from(this.el.nativeElement.files);
    this.imageUrl = 'https://i.pinimg.com/236x/d6/27/d9/d627d9cda385317de4812a4f7bd922e9--man--iron-man.jpg';
    this.editFile = true;
    this.removeUpload = false;
    this.registrationForm.patchValue({
      file: [null]
    });
  }
 
  // Submit Registration Form
  onSubmit() {
    this.submitted = true;
    if(!this.registrationForm.valid) {
      alert('Please fill all the required fields to create a super hero!')
      return false;
    } else {
      console.log(this.registrationForm.value)
    }
  }
}
Step 5: app.component.html
<div class="jumbotron text-center">
<h1 class="display-5">
How to upload image with Reactive Forms in Angular 7|8
</h1>
</div>
<div class="container">
<div class="row custom-wrapper">
<div class="col-md-12">
<!-- Form starts -->
<form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">
<div class="group-gap">
<!-- Upload image -->
<div class="avatar-upload">
<div class="avatar-edit">
<input type='file' id="imageUpload" accept=".png, .jpg, .jpeg" #fileInput (change)="uploadFile($event)" />
            </div>
            <div class="avatar-preview">
              <div id="imagePreview" [style.backgroundImage]="'url('+ imageUrl +')'">
              </div>
            </div>
          </div>
        </div>
          <!-- Submit Button -->
          <button type="submit" class="btn btn-danger btn-lg btn-block" (click)="fileInput.click()">Upload Image</button>
      </form><!-- Form ends -->
    </div>
  </div>
</div>
Result image
How to upload image with Reactive Forms in Angular 7|8

No comments:

Post a Comment