rmitula
rmitula

Reputation: 47

Angular default selected option

This is my 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>

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

And my problem is how to set default option in my select box. Let's say I want to select first element of my servers array.

Upvotes: 1

Views: 245

Answers (1)

Michael Doye
Michael Doye

Reputation: 8171

You can do the following - assign serverSelected a default value from your response:

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

Upvotes: 1

Related Questions