【问题标题】:Can't display options in select list using *ngFor in Angular 9无法在 Angular 9 中使用 *ngFor 在选择列表中显示选项
【发布时间】:2020-09-04 10:48:54
【问题描述】:

我无法在选择列表中显示选项。 HTML 代码如下:

  <select class="selectpicker" (change) = "searchCountry(selectedCountry)" [(ngModel)] = "selectedCountry" data-live-search="true" title = "Selecciona un país">
            <option [ngValue]="object" *ngFor = "let object of countryList" >{{object.Country}}</option> 
  </select>

我要做的是显示 countryList 数组中对象的属性“Country”(这是一个字符串)。 问题是没有选项显示,选择列表是空的。

我确定问题不在于 countryList,因为如果我在 select 元素之外运行以下代码,Country 属性会正确显示。

<h2>{{countryList[0].Country}}</h2>

我也试过用类似下面的数组替换 countryList,它显示正确,所以我不确定问题出在选择列表上。

countryList: Country[] = ["Argentina", "Chile", "Ecuador];

会不会和countryList数组的长度有关?它有 186 个元素。

【问题讨论】:

  • 无关,但尽量不要使用像objectnumber这样的变量名。它们可能(或可能不会)干扰 JS 数据类型。你可以说countryObj

标签: html angular html-select ngfor


【解决方案1】:

请试试这个:

<option *ngFor="let country of countryList" value="{{country}}">{{country}}</option>

如果 countryList 是

countryList: Country[] = ["Argentina", "Chile", "Ecuador];

【讨论】:

    【解决方案2】:

    正如您所展示的,countryList 是字符串数组,因此您不能像 object.Country 那样使用它,只需使用对象

    像下面这样使用

    <select [(ngModel)]="selectedCountry" (change) = "searchCountry(selectedCountry)">
        <option [value]="object" *ngFor="let object of countryList">{{object}}</option>
    </select>
    

    工作示例

    https://stackblitz.com/edit/angular-select-example-v6rndj?embed=1&file=app/app.component.html

    【讨论】:

      【解决方案3】:

      感谢您的回答,我已经部分解决了这个问题。

      代码没问题,问题是 HTML 代码中选择框的类。我删除了 'class="selectpicker"' 并且选择框开始显示所有选项。这个类来自 bootstrap-select,也许它不支持这种子句。

      所以代码是这样的:

      <select (change) = "searchCountry(selectedCountry)" [(ngModel)] = "selectedCountry"  title = "Selecciona un país">
                  <option *ngFor = "let countryName of countryList" >{{countryName.Country}}</option> 
      </select>
      

      我忘了提到 countryList 的元素是通过 HTTP GET 方法传递的,因此不能用字符串数组替换它。该问题可能是由 HTTP 响应延迟引起的。

      再次感谢。

      【讨论】:

        猜你喜欢
        • 2018-12-21
        • 1970-01-01
        • 2021-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多