Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 binding to a specific item in an array

I have an array of countries in an Angular template-driven form

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

I have a selected id in a model: 2

I want to bind the value "US" in a div. Something like this:

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

Is this possible in angular 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>
like image 610
Johannes Klapwijk Avatar asked Oct 19 '25 14:10

Johannes Klapwijk


1 Answers

you can create a getter property in the typescript and use it like this:

TS:

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

HTML

<div>{{ CountryCode }}</div>
like image 116
Ayman El Temsahi Avatar answered Oct 21 '25 05:10

Ayman El Temsahi