在Angular中将对象数组与ngFor一起使用

时间:2019-07-14 21:20:23

标签: html twitter-bootstrap typescript angular7

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

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>

1 个答案:

答案 0 :(得分:0)

这就是我所做的。

<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'},