Search code examples
angulartypescriptangular7angular-forms

How do i convert reader.result into string?


When I try to upload an image on angular three is an error on reader.result in bellow typescript file how can I fix this? I added console.log(image) in the function which is onImagePicked it also not shown in console why doesn't it show in the console?

typescript file

     imagePreview:string;


ngOnInit(){
  this.form = new FormGroup({
    title : new FormControl(null,{validators:[Validators.required]}),
    content: new FormControl(null,{validators:[Validators.required]} ),
    image: new FormControl(null, {validators: [Validators.required]})
  });


        onImagePicked(event: Event){
          const file = (event.target as HTMLInputElement).files[0];
          this.form.patchValue({image: file});
          this.form.get('image').updateValueAndValidity();
          console.log(file);
          const reader = new FileReader();
          reader.onload = () => {
            this.imagePreview = reader.result;
          };
          reader.readAsDataURL(file);
        }

Html file

<mat-card>
  <mat-spinner *ngIf="isLoading"></mat-spinner>
  <form [formGroup]="form" (submit)="onAddPost()"  *ngIf="!isLoading">
    <mat-form-field>
      <input matInput type="text" formControlName="title" placeholder="title"  >
      <mat-error *ngIf="form.get('title').invalid" >Please enter the Title</mat-error>
    </mat-form-field>

    <mat-form-field>
      <textarea matInput rows="6" formControlName="content" placeholder="caption"   ></textarea>
      <mat-error *ngIf="form.get('content').invalid" >Please enter the Content</mat-error>
    </mat-form-field>
<div class='image-preview'>
  <img src="" [alt]="form.value.title">
</div>


    <div>
        <button mat-stroked-button type="button" (click)="filePicker.click()">Add Image</button>
        <input type="file" #filePicker (chnage)="onImagePicked($event)">
      </div>

    <button  mat-raised-button color="accent" type="submit">Save Post</button>
</form>
</mat-card>

Solution

  • According to the official documentation for FileReader.result(), the type of the return value for that method might be of string, or ArrayBuffer.

    You might need use TypeScript's type assertion to tell the compiler that reader.result is of type string, since you have set the type for imagePreview as string.

    reader.onload = () => {
      this.imagePreview = reader.result as string;
    };