首页 > 解决方案 > Angular - 如何使用 ngFor 在选择选项之间添加分隔符?

问题描述

我正在使用 ngFor 用选项填充我的选择。

<select>
  <option *ngFor='let item of items; let i = index, [value]='item.name',)> {{ item.label }} </option>
</select>

我想在某个选项之后添加一个分隔符。所以像这样

Item1
Item 2
-- Divider --
Item 3

我已经通过使用索引来显示分隔符

<option *ngFor='let item of items; let i = index, [value]='item.name',)> {{ item.label }} {{ i == 2 ? '----' : ''}}</option>

但我似乎无法让它自己的路线。
关于如何做到这一点的任何提示?此外,任何关于如何拥有比 --- 更好看的分隔线的建议都将不胜感激。

谢谢!

标签: angularngfor

解决方案


*ngFor<ng-container>元素上使用。然后,您可以为每个数组项添加多个子元素。

例子:

<select>
  <ng-container *ngFor="let item of items;">
    <option [value]="item.value">{{item.name}}</option>
    <option *ngIf="item.name === 'foobar'" disabled="disabled">----</option>
  </ng-container>
</select>

推荐阅读