【问题标题】:Angular 9, 10 - Set Selected in option in DropdownAngular 9、10 - 在下拉列表中的选项中设置选定项
【发布时间】:2020-11-22 22:14:27
【问题描述】:

如果“* ngFor”循环中的值为“true”(取自组件 ts 文件中的 response.body),我如何在 HTML 选项中将属性设置为“Selected”

下拉代码:

<select [(ngModel)]="customer.id">
   <option *ngFor="let location of locations" [ngValue]="location.id"
       [selected]="location.isDefaultLocation === true? 'selected': ''">
       {{location.name}}
   </option>
</select>

也试过了:

<option *ngFor="let location of locations" [ngValue] ="location.id"
    [selected] ="location.isDefaultLocation === true">
    {{location.name}}
</option>

也尝试过 [compareWith]:

<select [compareWith]="locationFn" [(ngModel)]="customer.id">
   <option *ngFor="let location of locations" [ngValue]="location.id">
       {{location.name}}
   </option>
</select>

在组件 ts 文件中:

  locationFn(item1: any, item2: any): boolean {
    return item1.isDefaultLocation === true;
  }

不起作用但总是返回第一个值!!

【问题讨论】:

    标签: html typescript angular9 option angular10


    【解决方案1】:

    在组件文件中

    selectedLocationId:number = 4; // use default value here which you want to show selected
    

    HTML 文件

    <select [(ngModel)]="selectedLocationId">
       <option *ngFor="let location of locations" [value]="location.id">
           {{location.name}}
       </option>
    </select>
    

    【讨论】:

      猜你喜欢
      • 2017-10-06
      • 2018-02-10
      • 2019-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 2016-10-24
      • 1970-01-01
      相关资源
      最近更新 更多