0

I'm trying to add a filter to a dropdown

<select class="form-control" [ngModel]="value" (ngModelChange)="onChange($event)">
  <option selected value="0">{{ first_value }}</option>
  <option *ngFor="let i of data" [value]="i.id">
     {{i.city_name}}
  </option>
</select>

How can I add a filter like *ngIf="city_country == 'US'"?

6
  • Why not filter the data array with that condition? Commented May 22, 2021 at 17:48
  • 1
    Why do this in the template? Just filter the data array in the backing code. Commented May 22, 2021 at 17:48
  • @eko @R. Richards, Because depending on a env file, I'm trying to filter it on Frontend. For if env.name == 'X', if can display only city_country == 'US', if env.name == 'Y', I want to display only city_country == 'UK'. Commented May 22, 2021 at 17:52
  • This html is part of a component and that component has a data field, right? You can make this filtering operation in your component rather than doing it on the html. It doesn't matter where this filter is coming from. Your component.ts file still Frontend. Commented May 22, 2021 at 17:55
  • @eko Thanks. I have added the filter in my component. But is it not acceptable to add a check in HTML part? Commented May 22, 2021 at 18:34

1 Answer 1

1

As we are using structural directive we couldn't use two on same tag.

so either you can use new variable to get all the city's within US or we can have a get function to get all the city's with in US

// inside component class    
get citiesWithinUS() {
  return this.data.filter(x => x.city_country === 'US')
}


// inside html page
<select class="form-control" [ngModel]="value" (ngModelChange)="onChange($event)">
  <option selected value="0">{{ first_value }}</option>
  <option *ngFor="let i of citiesWithinUS" [value]="i.id">
     {{i.city_name}}
  </option>
</select>
Sign up to request clarification or add additional context in comments.

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.