0

My use case : I am assigning a Array of Objects to select's option using ngFor as follows

<select>
 <option *ngFor="let item of data" [value]="item.key">{{item.value}}</option>
<select>

and my data is

[
  {
    "key"   : "CHV",
    "value" : "Chivas"
  },
  {
    "key"   : "BLN",
    "value" : "Balentines"
  },
  {
    "key"   : "BDG",
    "value" : "Black Dog"
  }
]

Pretty straigtforward, now what i want is to bind the item.key and item.value specified by user i.e he should be able to mention which to use for options value and label. Here's what ive tried and didn't work

<option *ngFor="let item of data; let itemlabel = optionlabel; let itemvalue = optionvalue" value="{{item.itemvalue}}">{{item.itemlabel}}</option>

optionvalue & optionlabel are string in the component as follows

optionvalue : string = 'key';
optionlabel : string = 'value';

So now when i swap them i can get key as value and vice versa. Any idea how to do so

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Pratik Kelwalkar
  • 1,592
  • 2
  • 15
  • 21

1 Answers1

1

You could use the following:

<option *ngFor="let item of data" value="{{item[itemvalue]}}">
  {{item[optionlabel]}}
</option>

This way we would leverage the configuration done in your component.

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Works great! thanks, one more thing, im now trying to club the data based on user like this `` but the method is never called? any idea why – Pratik Kelwalkar May 17 '16 at 06:54
  • You're welcome! What is the `getClubbedOption` method? One of your component? – Thierry Templier May 17 '16 at 06:56
  • basically what i want to do is let the user mention what all data is to be clubbed while displaying the option. Yes `getClubbedOption` is a method of my component that should be called. `getClubbedOption(item : any) : any{ console.log(item); console.log(this.optionlabel) return "opt"; }` – Pratik Kelwalkar May 17 '16 at 06:59
  • 1
    The problem here is the use of the `this` keyword since when you reference a method, it becomes a function and you lose its execution context. I think that this question could help you: http://stackoverflow.com/questions/37213908/ng-lightning-data-object-is-undefined-on-lookup/37215762#37215762. Read the comments right after the question and you will see that the `lookup` method is used in the template... – Thierry Templier May 17 '16 at 07:05