【问题标题】:Angular 9: How to remove empty option from selectAngular 9:如何从选择中删除空选项
【发布时间】:2020-08-04 16:30:03
【问题描述】:

我正在使用 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>

谢谢!

【问题讨论】:

  • 确保将selectedValue 设置为null 而不是未定义或其他。
  • 是的,它设置为 null 但我仍然有这个空选项。
  • 如果您分配的值未包含在可能的选项中,则显示的选项也将为空/空白。示例:您的范围是 1 到 5,但 selectedValue 的当前值为 6。

标签: typescript angular9


【解决方案1】:

由于您希望在模板中选择的初始项目的值为null,因此您还需要将null 分配给绑定到字段ngModel 的字段的值。

  • 这与使用 undefined 不同,这将在 select 元素中产生一个空值。
  • 如果您分配的值未包含在可能的选项中,则显示的选项也将为空/空白。示例:您的范围是 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

【讨论】:

    猜你喜欢
    • 2021-01-20
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    相关资源
    最近更新 更多