0

I need to use a function expression in *ngFor like this,

<select>
  <option *ngFor="let item of getItems(someValue)">
  ..........
  </option>
</select>

Is there any issue in using a function like getItems(someValue) where I get the items based on the 'someValue'. Is this approach ok or should I use some other way?

Lokn
  • 421
  • 4
  • 17

2 Answers2

2

Its recommended that you dont use functions directly when binding to the UI, as these will be run every time the change detection lifecyle runs, possibly leading to poor performance.

Steve Land
  • 4,852
  • 2
  • 17
  • 36
  • I agree but my usecase is based on the someValue, I need to return different items say items 1...10 if someValue is 1 and items 11...20 if someValue is 2. In that case should I go ahead with using the function? – Lokn Jul 09 '18 at 10:50
  • If you're not too worried about performance you could do that, but it would be safer to bind to a property that you update when `someValue` is changed (which you could do by making it a private property and accessing it using getter/setter methods - example here: https://stackoverflow.com/a/12850536/7840778 ) – Steve Land Jul 09 '18 at 10:54
1

*ngFor should be used only for binding with an array declared in your component. If this array changes over time, that's ok because Angular knowns when to redraw the view based on your variables.

You can do this in your component:

public items: YourObject[];

You can assign the values in the constructor, or any other place:

constructor(){
  this.items = this.getItems(someValue);
}

Then just use it in the *ngFor like this: let item of items

Gijs Post
  • 199
  • 6
  • constructor ideally should never be used for initializing logic variables. Use ngOnInit instead. – Prachi Jul 09 '18 at 10:18
  • I agree but my usecase is based on the someValue, I need to return different items say items 1...10 if someValue is 1 and items 11...20 if someValue is 2. In that case should I go ahead with using the function? – Lokn Jul 09 '18 at 10:49
  • It doesn't matter. Angular updates your view when the array changes. You can assign the items using your method with someValue, and if you need a new set with a different someValue, just reassign the array by calling the method on it again. – Gijs Post Jul 09 '18 at 10:58