Advertisement
Guest User

angular upload reactive form

a guest
Mar 21st, 2019
514
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. @Component({
  2.   template: `
  3.     <form [formGroup]="formGroup" novalidate (ngSubmit)="onSubmit()">
  4.       <input type="file" (change)="onFileChange($event)" />
  5.       <button type="submit" [disabled]="formGroup.invalid || formGroup.prestine">Submit</button>
  6.     </form>
  7.   `
  8. })
  9. export class PizzaComponent {
  10.  
  11.   formGroup = this.fb.group({
  12.     file: [null, Validators.required]
  13.   });
  14.  
  15.   constructor(private fb: FormBuilder, private cd: ChangeDetectorRef) {}
  16.  
  17.   onFileChange(event) {
  18.     const reader = new FileReader();
  19.  
  20.     if(event.target.files && event.target.files.length) {
  21.       const [file] = event.target.files;
  22.       reader.readAsDataURL(file);
  23.  
  24.       reader.onload = () => {
  25.         this.formGroup.patchValue({
  26.           file: reader.result
  27.        });
  28.      
  29.         // need to run CD since file load runs outside of zone
  30.         this.cd.markForCheck();
  31.       };
  32.     }
  33.   }
  34.  
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement