简体   繁体   English

Angular 5绑定到数组中的特定项目

[英]Angular 5 binding to a specific item in an array

I have an array of countries in an Angular template-driven form 我有一个以Angular模板驱动形式的国家/地区

"countries" : [  
   {  
      "id":1,
      "code":"NL"
   },
   {  
      "id":2,
      "code":"US"
   }
]

I have a selected id in a model: 2 我在模型中有一个选定的ID:2

I want to bind the value "US" in a div. 我想将值“ US”绑定到div中。 Something like this: 像这样:

<div>{{countries[id==model.countryId].code}}</div>

Is this possible in angular 5? 角度5可能吗? I see on the web that a filter pipe for an array does not exist in angular anymore. 我在网上看到数组的过滤器管道不再存在于角度中。

I get it working like this, but this is not really nice i'd say: 我让它像这样工作,但这不是很好,我会说:

<ng-container *ngFor="let country of countries">
   <div *ngIf="country.id==parentModel.countryId">{{country.code}}</div>
</ng-container>

you can create a getter property in the typescript and use it like this: 您可以在打字稿中创建一个getter属性,并像这样使用它:

TS: TS:

get CountryCode() {
    let country = this.countries.find(x=>x.id == this.parentModel.countryId);
    return country && country.code;
}

HTML HTML

<div>{{ CountryCode }}</div>

ngx-pipes ( https://github.com/danrevah/ngx-pipes ) has some interesting pipes, for example filterBy , that you can use this way: ngx-pipeshttps://github.com/danrevah/ngx-pipes )有一些有趣的管道,例如filterBy ,您可以使用这种方式:

{{ countries | filterBy: ['id']: yourID }}

That returns the countries with the id you specify. 这将返回您指定ID的国家/地区。 It also has pipes for every situation 它还有适合各种情况的管道

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM