【问题标题】:Angular - How to add dividers in between select options using ngFor?Angular - 如何使用 ngFor 在选择选项之间添加分隔符?
【发布时间】:2019-02-13 14:49:39
【问题描述】:

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

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

谢谢!

【问题讨论】:

  • 虽然您的问题略有不同,但我认为链接的答案 stackoverflow.com/a/49324923/10747134 是您正在寻找的。基本上,除了您的选项之外,您还需要有另一个“块”,否则分隔符将包含在您的选项中。建议遵循该链接,但不要使用 div 使用 标记。这样,选项代码可以保留选项代码,并且在另一个块下方,您可以拥有您的分隔代码。

标签: angular ngfor


【解决方案1】:

&lt;ng-container&gt; 元素上使用 *ngFor。然后你可以为每个数组项添加多个子元素。

例子:

<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>

【讨论】:

  • 谢谢!这解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-08
  • 1970-01-01
  • 2014-07-08
  • 1970-01-01
  • 2020-12-21
相关资源
最近更新 更多