简体   繁体   中英

ngFor call function Angular2

The following works:

*ngFor="let child of items || []; let i = index;"

This doesn't:

*ngFor="let child of items || []; let specialVersionOfI = someFunction(index);"

I get:

Parser Error: Unexpected token (, expected identifier, keyword, or string at column 56 in [ngFor let child of items |

What's the reasoning behind this, and is there an alterantive?

Use the function later within the loop, not when you assign the index.

<u>
   <li *ngFor="let item of items || []; let i=index">
      use function here >> {{someFunction(i)}}
   </li>
</u>

You could also manipulate the array in the model and store the special index in a second parallel array, then access it within the template.

<u>
   <li *ngFor="let item of items || []; let i=index">
      access special index >> {{customIndices[i]}}
   </li>
</u>

Much more readable will be version with mapping in component, sth like:

this.items.map((child, i) => { child['specialVersionOfI'] = this.someFunction(i); return child; }) and then in template just {{child.specialVersionOfI}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM