Angular 2 - NgFor not updating view

10,559

Solution 1

The reason why you are still seeing your list is because it is async. You can't be sure when the subscribe method is executed. It can be be direct, within seconds, take hours or not even at all. So in your case you are resetting the list before you are even getting one.

constructor( private songService : SongService)
  this.songService.getSongs()
    .subscribe(songsList => { //Might take a while before executed.
      this.songs = songsList;
    });

  this.songs = null; //executed directly
}

The above explanation might be the cause of your problem, but there could also be another explanation. The constructor is only called when the component is created. Changing a router parameter doesn't necessarily create a component. Angular might re-use the component if it can.

Solution 2

Instead of null you should set an empty array, also have it inside a method, otherwise it never gets called

 this.songService.getSongs()
         .subscribe(songsList => {
             this.songs = songsList;
         });
clear(){
    this.songs = [];
}
Share:
10,559
Aviv Eyal
Author by

Aviv Eyal

Updated on June 04, 2022

Comments

  • Aviv Eyal
    Aviv Eyal almost 2 years

    I am working on angular 2 project and I am having an issue when I am trying to change the list . NgFor not recognizing the changes , and displaying only the list loaded at first time .

    here is an example code when I am loading all list and imminently after loading I reset it with null . the view still displaying all the list ...

    this is my component constructor for example :

     constructor( private songService : SongService)
        this.songService.getSongs()
             .subscribe(songsList => {
                 this.songs = songsList;
             });
    
        this.songs = null;
    
    }
    

    and this is the html :

    <div class="row">
        <div  *ngFor= "let song of songs" class="col-md-4">
         <app-song-item [song]="song"></app-song-item>
        <br>
        </div>
    </div>