【问题标题】:Using object array with ngFor in Angular在 Angular 中使用带有 ngFor 的对象数组
【发布时间】:2019-07-15 08:24:21
【问题描述】:

我有这个国家和国家代码的对象数组。

export class Countries {
  countryCode: object[] = [
    {
      name: 'Afghanistan',
      code: 'AF'
    },
    {
      name: 'land Islands',
      code: 'AX'
    }
  }

  CountryCode() {
    return this.countryCode;
  }
}

我是这样初始化的

countryList: object[] = new Countries().countryCode;

但我似乎无法访问 HTML 中的值 country.namecountry.code

错误在说

标识符“名称”未定义

这是我的ngFor

<div class="form-group">
   <select
      id="country" class="form-control">
      <option *ngFor="let country of countryList;" 
      [value]="country.code">
      {{country.name}}
      </option>
  </select>
</div>

【问题讨论】:

  • [value]="country.code" 替换为[ngValue]="country" 然后选择的值将是国家对象
  • 当我切换到ngValue时,如何获取名称和代码?尝试“country.name, country.code”显示错误
  • 你有没有尝试 console.log(countryList) 看看输出是什么?
  • countryList 是一个对象数组

标签: html twitter-bootstrap typescript angular7


【解决方案1】:

这就是我所做的。

<div class="form-group">
                      <select
                        id="country" class="form-control" >
                        <option *ngFor="let country of countryList" 
                          [value]="country.code" 
                          [selected]="country.name == 'United States'">
                            {{country.name}}
                        </option>
                      </select>
                    </div>

我把国家列表改成了这个

countryCode = [
    {name: 'Afghanistan', code: 'AF'},
    {name: 'land Islands', code: 'AX'}
 ];

来自

countryCode: object[] = [
    {name: 'Afghanistan', code: 'AF'},
    {name: 'land Islands', code: 'AX'},

【讨论】:

    猜你喜欢
    • 2020-09-23
    • 2019-04-22
    • 2018-08-13
    • 2021-03-28
    • 2019-07-20
    • 2017-04-07
    • 2019-02-12
    • 2018-08-29
    • 2020-12-19
    相关资源
    最近更新 更多