【问题标题】:How to show actual value in dropdown list and maybe set the other option from this list如何在下拉列表中显示实际值,并可能从此列表中设置其他选项
【发布时间】:2018-11-20 20:57:58
【问题描述】:

如何从下拉列表中显示实际选择的选项,并在拉伸列表后显示其他可用元素。现在我有一个只有可用元素的下拉列表,我可以选择元素。 HTML:

        <div class="pb-1">
          <label class="small">Car:</label>
          <select formControlName="Car" class="form-control">
              <option *ngFor="let x of cars" [ngValue]='x.id'>{{x.id}} : {{x.carName}}</option>
          </select>
        </div>

TypeScript:

export class PersonDetailsComponent implements OnInit {
 cars : Car[];
.
.
.
populateCars()
{
  this.personsService.getCars().subscribe(result => {
    this.cars = result;
});
}

personsService:

getCars() :Observable<Car[]>
    {  
        return this.http.get(this.apiUrl + 'AviableCars')
                        .map((result)=>result.json());
    };

【问题讨论】:

    标签: javascript angular typescript angular5 asp.net-core-webapi


    【解决方案1】:

    您需要使用 [selected] 属性。我还会添加一个“请选择”默认选项:

    <option value="" disabled selected> <!-- default selected -->
      Please select a car
    </option>
    <option *ngFor="let x of cars" [ngValue]='x.id' [selected]="Car.id === x.id">
      {{x.id}} : {{x.carName}}
    </option>
    

    [selected] 属性需要一个计算结果为真或假的表达式。如果为 true,它将在列表中突出显示该项目 (x.id)。

    因此,这里检查 Car.id(来自您的模型)是否与 *ngFor 中的 x.id 匹配 - 因此将为 ngFor 中的每个 x 评估表达式,其中一个当然应该为真。

    更多信息herehere

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多