Peter Charitopoulos
Peter Charitopoulos

Reputation: 63

Angular 9: How to remove empty option from select

I am using angular 9, building a dropdown with some options. I am trying to set the default one but in the load of the page, the dropdown has a blank option. How can I remove this blank option?

This is what I currently have:

<form #f="ngForm">
  <select aria-labelledby="dropdownMenuButton" [(ngModel)]="selectedValue" (change)="hideShowElements($event.target.value)">
    <option [ngValue]="null">Show All</option>
    <option *ngFor="let item of response.results | filterUnique;" [ngValue]="item.section">{{item.section}}</option>
  </select>
</form>

Thank you!

Upvotes: 4

Views: 9141

Answers (1)

Igor
Igor

Reputation: 62238

As the initial item you want selected in your template has a value of null then you need to also assign null to the value of the field bound to the field's ngModel.

  • This is not the same as using undefined, this will yield en empty value in the select element.
  • If you have a value assigned that is not contained as a possible option then the displayed option will also be empty/blank. Example: You have a range from 1 to 5 but the current value of selectedValue is 6.

app.component.ts

export class AppComponent  {
  selectedValue: number = null;
  selectedValue2: number;
}

app.html

<h3>Example with an assignment to null<h3>
<select aria-labelledby="dropdownMenuButton" [(ngModel)]="selectedValue">
  <option [ngValue]="null">Show All</option>
  <option [ngValue]="1">One</option>
  <option [ngValue]="2">Two</option>
</select>

<h3>Example with no assignment to null<h3>
<select aria-labelledby="dropdownMenuButton" [(ngModel)]="selectedValue2">
  <option [ngValue]="null">Show All</option>
  <option [ngValue]="1">One</option>
  <option [ngValue]="2">Two</option>
</select>

See also a working stackblitz example.

Upvotes: 4

Related Questions