Angular 默认选择的选项

Angular default selected option

这是我的 html:

<select
    [(ngModel)]="serverSelected"

    name="serverSelected"
    (change)="onServerSelect()"
    class="custom-select mb-2 col-md-4 col-12 mr-sm-2 mb-sm-0"
    >
    <option *ngFor="let server of servers" [ngValue]="server">{{server.display_name}}</option>
  </select>

我的server.component.ts:

ngOnInit(){
  this.getServers();
  this.getServerPackages(1);
  this.getServerCategories(1);
}
onServerSelect(serverSelected){
  console.log(this.serverSelected.display_name);
  this.getServerPackages(this.serverSelected.id);
  this.getServerCategories(this.serverSelected.id);
}
getServers(){
  this.serverService.getServers().subscribe(response => {
    this.servers = response;
    console.log(response);
  });
}

我的问题是如何在 select 框中设置默认选项。假设我想 select 服务器数组的第一个元素。

您可以执行以下操作 - 从您的回复中分配 serverSelected 默认值:

getServers(){
  this.serverService.getServers().subscribe(response => {
    this.servers = response;
    this.serverSelected = response[0]; // set the selected option to the first of the array
    console.log(response);
  });
}