【问题标题】:Angular 4 - ngfor with ngif errorAngular 4 - 带有 ngif 错误的 ngfor
【发布时间】:2018-03-25 15:55:03
【问题描述】:

我正在开发 anuglar 4 项目,其中数据在组件中获取 在选择 html 中循环遍历它,但我想根据它的名称将特定选项标记为选中

代码

<select class="form-control" id="exampleSelect1">
    <option  *ngFor="let field of fields" *ngIf="field.name == 'Select me'; then selected='true'">{{field.name}}</option>
</select>

但在将 ngif 与 ngfor 一起使用时它不起作用

错误

Error: Template parse errors:
Can't have multiple template bindings on one element. Use only one attribute named 'template' or prefixed with *

【问题讨论】:

  • 代替 *ngIf 你可以使用 [selected]="field.name==='Select me'" 属性来选择选项
  • @JayDeeEss 有正确的想法。这真的,真的不是ngIf 的用途。

标签: angular


【解决方案1】:

您可以使用 [selected]="field.name==='Select me'" 属性而不是 ngIf 来选择选项

<select class="form-control" id="exampleSelect1">
        <option  *ngFor="let field of fields" [selected]="field.name==='Select me'">{{field.name}}</option>
    </select>

【讨论】:

  • 如果您不想显示该属性,您应该返回null。我认为这样,每个选项都会有 selected 属性。
  • 您绝对可以这样做,但这也可以,因为对于所有其他不匹配的内容,它将返回 false 并且无论如何都不会被选中!
猜你喜欢
  • 2016-09-17
  • 2018-01-22
  • 2018-06-17
  • 2019-09-18
  • 2020-11-06
  • 1970-01-01
  • 2020-06-21
  • 2023-04-02
  • 2018-02-13
相关资源
最近更新 更多