1

这是我的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);
  });
}

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

4

1 回答 1

1

您可以执行以下操作 -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);
  });
}
于 2017-11-26T19:08:53.750 回答