Ben Phung
Ben Phung

Reputation: 346

How to do dynamic expression in ngFor?

I have an array of objects (list: any[]) that I use in an *ngFor expression. Is it possible to display one of the properties from the object when I know the property name at runtime?

I am creating a component, called ListComponent that displays a list of items. The parent component called ParentComponent, will pass in the array of objects and the property that it wants the ListComponent to display in the list. Here is what I have so far in the ListComponent:

<div>
<div class="item" *ngFor="let item of itemList">{{item.name}}</div>
</div>

Instead of {{item.name}}, is it possible to make the .name part dynamic and use the property passed in by ParentComponent?

Upvotes: 3

Views: 2222

Answers (3)

arun kumar
arun kumar

Reputation: 1171

Component

  @Input()  parentKey
  itemList=[{key:'State',value:'state'},
  {key:'Severity',value:'severity'},
  {key:'Priority',value:'priority'},
  {key:'Category',value:'categorization'},{key:'Owner',value:'owner'}

HTML

<div>
<div class="item" *ngFor="let item of itemList">{{item[parentKey]}}</div>
</div>

Stackblitz link: https://stackblitz.com/edit/angular-fakfmp?file=src/app/app.component.html

Upvotes: 0

Dhananjai Pai
Dhananjai Pai

Reputation: 6015

You could create a 'dynamicKey' variable in your .ts that changes and access it like below. You could also optionally provide a default or empty string for the case it is undefined.

<div>
    <div class="item" *ngFor="let item of itemList">{{item[dynamicKey] || ''}}</div>
</div>

Another approach may be to create an array from the object based on your dynamic key, to reduce logic in the templates.

dynamicArray = itemList.map(item => item[dynamicKey])
<div>
    <div class="item" *ngFor="let item of dynamicArray">{{item}}</div>
</div>

Upvotes: 1

Venkatesh K
Venkatesh K

Reputation: 721

try with the below code. here name is variable which can be dynamic from component.

<div>
<div class="item" *ngFor="let item of itemList">{{item[name]}}</div>
</div>

Upvotes: 0

Related Questions