Adding items to array for primeng dropdown does not update the rendred dropdown
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 ?
save
newGame()
No, thats not it
– devzero
Aug 25 at 15:44
Does the initial values work fine in the drop-down (before adding a new game)? If yes, can you log the
r
value in the onInit, as well as the game
you try to push and show us the result?– abdullahkady
Aug 25 at 15:46
r
game
1 Answer
1
Check this StackBlitz: Dropdown example
HTML file:
<p-dropdown [options]="games" [(ngModel)]="selectedGame" optionLabel="name" #acc></p-dropdown>
<button pButton type="button" label="New game" (click)="newGame(acc)</button>
TS file:
interface Game
name: string;
export class AppComponent
games: Game ;
selectedGame: Game;
constructor()
this.games = [
name:'Game1',
name:'Game2',
name:'Game3'
];
newGame(acc)
let newGame: Game = name: "NEW GAME" ;
this.games.push(newGame);
acc.options = this.games;
What is #acc and acc.options?
– devzero
Aug 25 at 15:43
The #acc is a 'template reference variable' check this in the Angular documentation (angular.io/guide/…). So acc is a reference to the dropdown element, therefore acc.options is only an access to the 'options' property of the primeng dropdown element, you can check all of the properties here (primefaces.org/primeng/#/dropdown).
– Juan
Aug 25 at 16:52
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Maybe your subscription in the onInit "getListOfGames()" fires again when you call the
save
function in thenewGame()
, thus resetting your games property?– abdullahkady
Aug 25 at 14:42