在 angular ivy 中是否可以在 select 中没有预 selected 条目

Is it possible to have no preselected entry in select in angular ivy

在我的 angular 应用程序中,我使用 select 控件让用户在 *ngFor 循环中选择填充选项。对于第一次调用(或直到用户设置实际值),selection 为空,一旦创建 selection,他们可以更改值但不能将其设置回 "empty" .这就是它的设计和工作方式,直到 angular 8.

直到 ng 8 我的代码看起来像这样,只要 someValue 为空,select 控件中就没有预 select 条目:

<select [value]="someValue" (change)="onSelectionDataChanged($event.target.value)">
  <option *ngFor="let option of options" [value]="option"> {{ option }} <option>
</select>

使用 ivy 不再可能将 <select [value]=...><option *ngFor=...> 一起使用(参见 https://angular.io/guide/ivy-compatibility-examples#select-value-binding),但那里给出的解决方案总是 selects 第一个条目甚至如果 someData 为空。这有两个缺点:1. 显示暗示第一个条目是 selected,这是不正确的 2. 实际上 select 第一个条目(并保存 selection 用于后端)用户现在必须先 select 第二个条目,然后 select 第一个条目。

修改后的代码(如 angular 指南中所建议)如下所示:

<select (change)="onSelectionDataChanged($event.target.value)">
  <option *ngFor="let option of options" [value]="option" [selected]="option === someValue"> {{ option }} <option>
</select>

一种解决方法是向选项数组添加一个空字符串,但这使用户能够完全删除他们的 selection。

有没有办法在 ivy 中选择空前select离子?

答案 对我有用:

只需添加一个带有隐藏和禁用设置的选项:

<select (change)="onSelectionDataChanged($event.target.value)">
  <option hidden disabled [selected]="!someValue" value=""></option>
  <option *ngFor="let option of options" [value]="option" [selected]="option === someValue"> {{ option }} <option>
</select>