Whenever I attempt to upload an image on Angular, I encounter an error with reader.result in the TypeScript file below. How can I resolve this issue?
I even included console.log(image)
in the onImagePicked function but it doesn't display anything in the console. Why isn't it showing?
Here is the 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);
}
Here is the 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>