Reputation: 63
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
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
.
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