Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding items to array for primeng dropdown does not update the rendred dropdown

I'm trying to add a new item to a angular dropdown.

export class ClansOfCaledoniaComponent implements OnInit {
  public selectedGame: ClansGame;
  public games = new Array<ClansGame>();

  constructor(private readonly clansOfCaledoniaService: ClansOfCaledoniaService ) { }

  ngOnInit() {
    this.clansOfCaledoniaService.getListOfGames().subscribe(r => {
      this.games = r;
      this.selectedGame = this.games[0];
    });
  }
  newGame() {
    var game = new ClansGame();
    game.name = `Game ${this.games.length + 1}`;
    let p = new Array<ClansPlayer>();
    p.push(new ClansPlayer());
    game.players = p;
    this.clansOfCaledoniaService.save(game).subscribe(a => {
      game.id = +a.status;
      this.games.push(game);
      this.selectedGame = game;
      console.log(game);
    });
  }
}

The HTMl I'm using

  <div class="ui-g-2">
    <p-dropdown [options]="games" [(ngModel)]="selectedGame" optionLabel="name"></p-dropdown>
  </div>
  <div class="ui-g-2">
    <button pButton type="button" label="New game" (click)="newGame()"></button>
  </div>

For some reason the dropdown is not updated when I push the new game. How can I update the array ?

like image 356
devzero Avatar asked Aug 25 '18 13:08

devzero


1 Answers

TIL that you have to replace arrays and all non-primitive types in order to trigger the binding mechanisms of Angular (coming from WPF and still shaking my head ;) ). So, instead of pushing to your array, just replace it and it should work:

this.clansOfCaledoniaService.save(game).subscribe(a => {
  game.id = +a.status;
  this.games = [...this.games, game];
  this.selectedGame = game;
  console.log(game);
});

Don't use the hack by accessing your template and updating the binding manually.

like image 93
Papa Mufflon Avatar answered Nov 15 '22 10:11

Papa Mufflon