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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With