Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 refresh <img src={{ ... }} > when the value changes

I am using Angular 4 and I have a component where I want to change my user current photo.. so the html code that displays the current user photo is this..

<div class="profilphoto">
        <img src= {{currentphoto}}>
</div>

currentphoto contains the current user photo url and I get it from firebase.. After that I display a Gallery of photos so the user can select one and change his profil photo using a form.. the submit code is the following and works fine

    onSubmit = function(form) {
    this.photoUrl = form.photoUrl;
    firebase.database().ref("users/"+this.authService.cusername+"/photo").update({
      url: form.photoUrl
    }).then(()=>{
      this.currentphoto = this.authService.photourl;
      console.log("currentphoto:"+this.currentphoto);
    }
    );
  }

Everything works fine except that despite the currentphoto value has changed and database url upadated the html still displays the previous user's image and its annoying(if I refresh the page it shows the new profil image).. Is there any way I can make

<div class="profilphoto">
        <img src= {{currentphoto}}>
</div>

detect when currentphoto changes value and Display the image with the new src value??

like image 363
Vasilis Michail Avatar asked Oct 10 '17 16:10

Vasilis Michail


3 Answers

This is probably not relevant anymore but in case it could help people get this solved faster, here it is.

If you want to update the image after it has changed write your src like this:
src='{{currentphoto}}?d={{clock_tick}}'

Initialize your clock tick when you first load your component (I use Date.now()) and again after you update the image. This will tell your browser that you updated the image and it will reload it for you.

It worked for me.

like image 96
Jean-Francois Bertrand Avatar answered Nov 15 '22 23:11

Jean-Francois Bertrand


Try calling the changedetection manually,

constructor(private cdRef: ChangeDetectorRef){

}

Once you set the image

 this.currentphoto = this.authService.photourl;
 this.cdRef.detectChanges();
like image 22
Sajeetharan Avatar answered Nov 15 '22 23:11

Sajeetharan


Without the entire code of your component/service is hard to know what is the problem, but the best shot is in this line:

onSubmit = function(form) {

probably it's a problem with the 'this' value. Insert a console.log(this) below this line (inside the function) and check if 'this' is a reference to the component instance or to the window.

Try to use arrow function:

onSubmit = form => {
 //do what you need here, call the service, etc...
 //and then set the this.currentphoto
}
like image 1
Christian Benseler Avatar answered Nov 15 '22 23:11

Christian Benseler