Aviv Eyal
Aviv Eyal

Reputation: 307

Angular 2 - NgFor not updating view

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>

Upvotes: 3

Views: 12362

Answers (4)

user4676340
user4676340

Reputation:

Loops in Angular sometimes screw up, in the way that they don't track your items the way you would want it to.

To prevent that, you can use a custom track by function like this

<div *ngFor="let song of songs; let i = index; trackBy: customTB" class="col-md-4">

In your TS

customTB(index, song) { return `${index}-${song.id}`; }

This way, you set up a custom trackBy function, that will update your view (the view wasn't getting updated because the tracking ID wasn't changing).

Upvotes: 6

Robin Dijkhof
Robin Dijkhof

Reputation: 19288

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.

Upvotes: 2

Rahul Sharma
Rahul Sharma

Reputation: 10081

Try this

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

reset() {
    this.songs = [];
}

Upvotes: -1

Sajeetharan
Sajeetharan

Reputation: 222582

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 = [];
}

Upvotes: 1

Related Questions