如何使占位符在选择中始终可见?

我在Angular应用程序中有一些选择。我想在其上放置一个占位符,此外,必须在特定条件下禁用整个选择。

到目前为止,这是我的代码:

<select class="form-control" id="food" [(ngModel)]="myFood" disabled="{{foodStatus === 'private'}}">
    <option value="" disabled="true" [selected]="true">Placeholder</option>
    <option value="1">Meat</option>
    <option value="2">Vegetarian</option>
    <option value="3">Vegan</option>
    <option value="4">Main dish</option>
</select>

At the moment, the disabled tag won't work. It does if I add a name to the select itself. But if I do it, the placeholder won't be visible but only present among the options when I pick one: it looks like a functionality breaks the other.

我在这里想念什么?

评论
  • 北城=忆
    北城=忆 回复

    您应该绑定到disabled属性:

    <select [attr.disabled]="foodStatus === 'private' ? 'disabled' : null">
    </select>
    

    请注意,如果不应该添加disabled属性,则需要设置null。在html中,仅存在disabled属性将使select禁用。

    另一个问题是您正在混合角度隐喻-[[ngModel)]确定选择哪个值。

    See this stackblitz for a working example. Note how I've removed [selected] from the first option.