4

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>
2
  • what is the expected one can you please explain in detail? Commented Feb 1, 2018 at 9:05
  • I expect to get <div>US<div> in de dom as result. Commented Feb 1, 2018 at 9:25

3 Answers 3

8

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.