Angular默认选择选项

时间:2017-11-26 19:04:50

标签: angular ng-options ngfor angular-ngselect

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

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

1 个答案:

答案 0 :(得分: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);
  });
}