将数组添加到数组以进行Primeng下拉列表不会更新更新的下拉列表

时间:2018-08-25 13:46:48

标签: angular primeng

我正在尝试向角度下拉列表中添加新项目。

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);
    });
  }
}

我正在使用的HTMl

  <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>

由于某种原因,当我推送新游戏时,下拉列表没有更新。如何更新数组?

2 个答案:

答案 0 :(得分:2)

您必须替换数组以及所有非基本类型,才能触发Angular的绑定机制(来自WPF并仍然摇摇头;))。因此,与其替换到您的数组,不如直接替换它,它应该可以工作:

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

不要通过访问模板并手动更新绑定来使用黑客。

答案 1 :(得分:1)

检查此StackBlitz:Dropdown example

HTML文件:

<p-dropdown [options]="games" [(ngModel)]="selectedGame" optionLabel="name" #acc></p-dropdown>

<button pButton type="button" label="New game" (click)="newGame(acc)</button>

TS文件:

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;
  }
}