我正在尝试向角度下拉列表中添加一个新项目。
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);
});
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用的 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>
Run Code Online (Sandbox Code Playgroud)
出于某种原因,当我推送新游戏时,下拉列表没有更新。如何更新数组?
Pap*_*lon 14
直到你必须替换数组和所有非原始类型才能触发 Angular 的绑定机制(来自 WPF 并且仍然摇头;))。因此,不要推送到您的数组,只需替换它即可:
this.clansOfCaledoniaService.save(game).subscribe(a => {
game.id = +a.status;
this.games = [...this.games, game];
this.selectedGame = game;
console.log(game);
});
Run Code Online (Sandbox Code Playgroud)
不要通过访问模板并手动更新绑定来使用 hack。