通过占位符传递元素

时间:2019-01-31 10:47:29

标签: angular ionic-framework ionic4

我是Ionic的新手,正在创建一段代码,为选择框生成选项。

我创建了一个json数组,其中包含国家代码等数据。

{
    "Countries":
              [
                {
                    "Country": "Nederland",
                    "Countrycode": "NL",
                    "Languagecode": "nl-nl"
                },{
                    "Country": "United Kingdom",
                    "Countrycode": "UK",
                    "Languagecode": "gb-en"
                },{
                    "Country": "Deutschland",
                    "Countrycode": "DE",
                    "Languagecode": "de-de"
                }
              ]
}

我创建了一个for循环,该循环为每个国家/地区创建了元素。该代码如下所示:

for (let index = 0; index < this.languages.Countries.length; index++) {
      if(this.languages.Countries[index].Languagecode !== undefined || this.languages.Countries[index].Country !== undefined){
        this.countryoptions += "<ion-select-option value="+this.languages.Countries[index].Languagecode+">"+this.languages.Countries[index].Country+"</ion-select-option>";
      }
    }

上面的方法效果很好,它可以输出元素,当我直接复制并粘贴输出时,选择框效果很好。但是,当我使用 {{countryoptions}} 时,它会添加“ undefined ... OUPUT ...”(OUTPUT表示来自for循环的输出),然后选择框不起作用。我尝试使用.replace();删除“”标记。但没有成功。

我也可以给出循环的输出,但是我的问题已经大部分是代码了。因此,我认为我可以忽略这一点。如果没有,请告诉我:)

因此,我要重提我的问题:

我如何通过占位符{{}}传递变量,而又不添加破坏元素的引号?

亲切的问候, 罗伯特

1 个答案:

答案 0 :(得分:1)

您应该直接在html模板中实现循环。

<ion-select-option *ngFor="let country of languages?.Countries" [value]="country.Languagecode">
  {{country.Country}}
</ion-select-option>

假设您有一个对象languages,其中包含名为Countries的属性,该属性是一个数组。

可观察的方式

如果使用http检索值,则将返回Observable<YourDataType>。在这种情况下,还应该使用内置的async角度管道。

<ion-select-option *ngFor="let country of (languages$ | async)?.Countries" [value]="country.Languagecode">
相关问题