【问题标题】:Unable to select value in option (Angular dropdown list.)无法在选项中选择值(角度下拉列表。)
【发布时间】:2019-08-02 21:34:41
【问题描述】:

我已经搜索过很多地方。我从other answers 得到的是,如果我想选择一个特定的选项,我需要使用[selected]

它似乎不起作用。为什么? 这是我所拥有的:

<ngx-datatable-column name="status" prop="operationStatus" [flexGrow]="1">
    <ng-template let-value="value2" let-row="row" let-rowIndex="rowIndex" gx-datatable-cell-template>
          <select class="geraeteStatus" [(ngModel)]="selectableGerateStatus">
             <option *ngFor="let e of selectableGerateStatus" [ngValue]="e" 
                 [selected]="e.id === value2">
                {{e.id}}
             </option>
          </select>
   </ng-template>
</ngx-datatable-column>

我确信e.id 的值每次迭代至少等于value2 的值一次。然而,它只是不起作用。 实际上,我可以将任何我想要的(e.id === 2,甚至'true')放入[selected],它没有任何效果。 我不知道我错过了什么。任何答案都非常感谢。

【问题讨论】:

  • 如果您使用的是 [(ngModel)],则不得使用 [selected]。问题是您使用的是 [ngValue]="e"。所以,变量“selectableGenerateStatus”是一个对象——你真的需要它是同一个对象。使用 [ngValue]="e.id" 工作
  • 好的,我明白了。我删除了“选定”。我更改为以下内容: 。但是还是不行

标签: angular select html-select


【解决方案1】:

您的选项中无需使用 [selected]

只需进行如下更改

Component.html

<select class="geraeteStatus" (change)="onChange($event)" [(ngModel)]="selectedStatus">
   <option *ngFor="let e of selectableGerateStatus" [ngValue]="e.id">
     {{e.id}}
   </option>
</select>

但这里你需要将ngValue 与你的ngModel 匹配,然后才会选择它。

Component.ts

selectedStatus: string;

onChange(status: string) {
   this.selectedStatus = status;
}

有关选择选项的更多信息check here

【讨论】:

  • 感谢 gnaesh045。不幸的是它仍然无法正常工作。
【解决方案2】:

如下所示将选项与 value 而不是 ngValue 绑定。

<select class="my-status" [(ngModel)]="myModel.status">
         <option [ngValue]="null" selected disabled> Select Status </option>
         <option *ngFor="let e of selectableGerateStatus" [value]="e">
            {{e.id}}
         </option>
</select>

【讨论】:

    【解决方案3】:

    我介绍了我是如何解决这个问题的。请注意,我对 Angular 很陌生,我的方法可能是初级的。我还要感谢@Eliseo,他强调了 ngModel 和 selected 不能一起使用这一事实。这就是我摆脱前者并仅使用选定的原因:

    component.html

     <select class="geraeteStatus" (change)="changeGaerateStatus($event, rowIndex)">
              <option *ngFor="let e of selectableGerateStatus" [selected]="value == e.id">
                   {{e.label}}
                </option>
     </select>
    

    和 .ts 文件:

        this.selectableGerateStatus = [
      {
        id: 0,
        label: BaseDataComponent.NEW
      }, {
        id: 1,
        label: BaseDataComponent.ACTIVE
      }, {
        id: 2,
        label: BaseDataComponent.DEINSTALLED
      }
    ]
    

    它解决了我的问题,但它可能不是最好的方法。随意发表评论。

    【讨论】:

      猜你喜欢
      • 2021-08-29
      • 1970-01-01
      • 1970-01-01
      • 2016-10-13
      • 2016-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-13
      相关资源
      最近更新 更多