【问题标题】:Selected not work in Angular 2 select选择在 Angular 2 中不起作用
【发布时间】:2018-08-14 04:18:54
【问题描述】:

angular 2 代码中使用 ngFor 填充选项的下拉菜单。我需要默认选择任何给定索引处的任何特定选项。

我使用过 [attr.selected]="i == 0" ,但它选择最后一个选项而不是第一个。

这是我的代码

<select id="roles" required formControlName="userRole">
    <option *ngFor="let roles of URoles;let i = index" [attr.selected]="(i==0)" [value]="roles._id">{{ roles.name }}</option>
</select>

可能是什么问题?为什么没有选择第一个选项?

【问题讨论】:

标签: angular typescript angular2-template


【解决方案1】:

请试试这个

<select id="roles" required formControlName="userRole">
    <option *ngFor="let roles of URoles" [selected]="roles._id == 0" [value]="roles._id" >{{ roles.name }}</option>
</select>

为我工作。希望这对你有用。

【讨论】:

    【解决方案2】:

    这可能对你有帮助

    <select id="roles" required formControlName="userRole">
     <option *ngFor="let roles of URoles;let i = index;" [value]="roles._id" selected="i==0">{{roles.name}}</option>
    </select>
    

    这里也不需要ng-container

    答案 2 - 如果您需要 attr.selected 属性才能使用,请使用以下代码:

    <select id="roles" required formControlName="userRole">
     <option *ngFor="let roles of URoles;let i = index;" [value]="roles._id" [attr.selected]="i == 1">{{roles.name}}</option>
    </select>
    

    【讨论】:

    • 所提供的解决方案有任何问题吗?
    【解决方案3】:

    据我了解,选择正在正常工作。所以一个简单的解决方案将是

    <ng-container *ngFor="let roles of universityAllRoles;let first = first"<option [attr.selected]="first" [value]="roles._id">{{ roles.name }}</option></ng-container>
    

    【讨论】:

      猜你喜欢
      • 2017-12-08
      • 2016-05-15
      • 1970-01-01
      • 2018-06-27
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多