Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Image Without Reloading in Angular 2/4

How can i change the image in angular without reloading the page? I have several users and every change in users also has change in image. right now, i need to reload the page to actually see the image change. How not to make it reload anymore?

ts

 private image1 = `assets/images/image${localStorage.getItem('user_id')}.jpg`;

html

<img [src]="image1">

select user.ts

onSelectUser(form: NgForm) {
    const user = form.value.org;
    this.userService.selectedUser(user)
        .subscribe(
          data => {
            console.log(data);
            localStorage.setItem('user_id', data.user.id);

          },
          error => {
             console.log(error);
          });
  }

1 Answers

A simple way to trigger image loading is to reassign src and trigger change detection, for example with setTimeout:

this.userService.selectedUser(user)
    .subscribe(
      data => {
        localStorage.setItem('user_id', data.user.id);
        this.image1 = '';
        setTimeout(() => {
          this.image1 = '...jpg';
        });

      },
      ...

Of course, this depends on caching. If image URL stays the same and server caching policy allowed it to be cached (usually this is true for images), it will still loaded from cache. In this case browser cache should be busted with URL change, similarly to how jQuery does for AJAX requests.

Considering that a server is ok with requests that add query string to the URL (usually this isn't a problem), it's simply:

this.userService.selectedUser(user)
    .subscribe(
      data => {
        localStorage.setItem('user_id', data.user.id);
        this.image1 = '...jpg?_=' + Date.now();
      },
      ...
like image 137
Estus Flask Avatar answered Sep 17 '26 20:09

Estus Flask