Thêm image preview trước khi upload trong Angular

Để hiển thị xem trước hình ảnh khi bạn vừa upload lên trong Angular ta thực hiện dễ dàng với code sau.

Giải pháp

Code bên trong file create.component.ts:

selectedFile: File | undefined;
  imageSrc: string | undefined;
  isImageChange: boolean | undefined;
  
myForm = new FormGroup({
    file: new FormControl('', [Validators.required]),
    fileSource: new FormControl('', [Validators.required])
  });
  
constructor() { }

get f(){
    return this.myForm.controls;
  }


onFileChange(event: any) {
    const reader = new FileReader();
    this.selectedFile = event.target.files[0];
    
    if(event.target.files && event.target.files.length) {
      const [file] = event.target.files;
      reader.readAsDataURL(file);
    
      reader.onload = () => {
   
        this.imageSrc = reader.result as string;

        this.isImageChange = true;
     
        this.myForm.patchValue({
          fileSource: reader.result
        });
   
      };
   
    }
  }
  
  submitCreateImage(id: string) {
    var formData = new FormData();
    formData.append( "file", this.selectedFile!);

    this.courseService.createImage(id, formData).subscribe(res => {
      console.log(res)

      this.ngZone.run(() =>
        this.router.navigateByUrl('admin/course/index')
      );
    }, (err) => {
      this.ngZone.run(() =>
        this.router.navigateByUrl('admin/course/index')
      );
    });
  }

Trong HTML chỉ cần bắt event như sau:
<input type="file" (change)="onFileChange($event)" />

Không có nhận xét nào:

Đăng nhận xét