jeudi 7 octobre 2021

image file upload in angular

I have image file upload input with preview for showing uploaded image file. There I need to handle some conditions like follow:

  1. show default image if image file is not selected and database doesn't have image, else show according images
  2. if database have image show that in preview then after file upload selected then show uploaded file in preview

I am not getting how I can handle these condition on src of img tag.

angular html code

<div class="profile_img">
    <div class="img">
        <img [src]="url?url:defaultUserProfileUrl" alt="Profile Image" class="img-fluid">
    </div>
    <div class="form-group">
        <div class="custom-file">
            <input type="file" id="myfile" name="myfile" [formControl]="profile_image" [(ngModel)]="currentInput"
            accept='image/*' (change)="onFileSelected($event)" />
        </div>
    </div>
</div>

if database image is present then I show like below:

<img [src]="userdata.profile_path?userdata.profile_path:defaultUserProfileUrl" alt="Profile Image " class="img-fluid" />

angular ts code

  url: any = [];
  defaultUserProfileUrl:string = 'assets/images/default_user_profile.png';
  onFileSelected(event) {
    console.log(event.target.files[0]);
    this.currentInput = event.target.files[0];

    if (event.target.files && event.target.files[0]) {
      var reader = new FileReader();

      reader.readAsDataURL(event.target.files[0]); // read file as data url

      reader.onload = (event) => {
        this.url = event.target.result;
      };
    }
  }

How I can handle multiple/nested if else conditions in src of image? or is there any other solution for this?

Please guide and help. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire