Angular 9:如何从 select 中删除空选项
Angular 9: How to remove empty option from select
我正在使用 angular 9,构建一个带有一些选项的下拉菜单。我正在尝试设置默认值,但在页面加载时,下拉列表有一个空白选项。我怎样才能删除这个空白选项?
这是我目前拥有的:
<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>
谢谢!
由于您希望在模板中 selected 的初始项的值为 null
,因此您还需要将 null
分配给绑定到该字段的字段的值ngModel
。
- 这与使用 undefined 不同,这将在 select 元素中产生空值。
- 如果您分配的值未包含在可能的选项中,则显示的选项也将是 empty/blank。示例:您的范围是 1 到 5,但
selectedValue
的当前值为 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>
另见工作 stackblitz example。
我正在使用 angular 9,构建一个带有一些选项的下拉菜单。我正在尝试设置默认值,但在页面加载时,下拉列表有一个空白选项。我怎样才能删除这个空白选项?
这是我目前拥有的:
<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>
谢谢!
由于您希望在模板中 selected 的初始项的值为 null
,因此您还需要将 null
分配给绑定到该字段的字段的值ngModel
。
- 这与使用 undefined 不同,这将在 select 元素中产生空值。
- 如果您分配的值未包含在可能的选项中,则显示的选项也将是 empty/blank。示例:您的范围是 1 到 5,但
selectedValue
的当前值为 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>
另见工作 stackblitz example。