Johannes Klapwijk
Johannes Klapwijk

Reputation: 91

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>

Upvotes: 4

Views: 2789

Answers (3)

wEsS__WeSs
wEsS__WeSs

Reputation: 1

For anyone else trying to make this work, you can create a pipe for it like this , feel free to make it as clean as possible

transform(value: any[], id: any): any {
 // I initialized country to an array because filter returns an array with one object

 let country: any = [];

 name = value.filter((item: any) => {
     if (item.id === Number(id)) {
       return item;
     }
 });

  // this returns the country code as a string
  return name[0] ?.code;
}

Then on the HTML just bind like this

{{ countries | getCountryCode : model.countryId}}

Upvotes: 0

Ayman El Temsahi
Ayman El Temsahi

Reputation: 2610

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>

Upvotes: 8

Gianluca Paris
Gianluca Paris

Reputation: 1429

ngx-pipes (https://github.com/danrevah/ngx-pipes) has some interesting pipes, for example filterBy, that you can use this way:

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

That returns the countries with the id you specify. It also has pipes for every situation

Upvotes: 0

Related Questions