Hello I am using Angular2 and wanted to fetch the server and get some values for each ID I get inside ngFor.
How about changing data before it comes to *ngFor
in Typescript itself,
this.items.forEach((item,index)=>{
item=this.func(item,index);
})
func(item,index):string{
return item+ String(index); //do whatever you wish to do.
}
The template is not the place to do that, you want to get your data in the component code. Sounds like you want to use something like flatMap
of an observable, which lets you return another observable for each item in the source observable. This could be the returns of an http api call or whatever (fiddle):
var ids = ["a", "d", "c"];
var lookupValues = { "a": 123, "b": 234, "c": 345, "d": 456 };
// given an id
function fakeApiCall(id) {
// given an id, return an observable with one entry: an object consisting
// of an 'id' property with that id value and a 'lookup' property with the
// value from lookupValues for that id
return Rx.Observable.just({ id: id, lookup: lookupValues[id] });
}
var o1 = Rx.Observable.from(ids); // 'a, d, c
var o2 = o1.flatMap(x => {
// here we get each value from o1, so we do an api call and return
// an observable from each that will have the values in that
// observable combined with all others to be sent to o2
return fakeApiCall(x);
});
o2.subscribe(x => {
document.write(JSON.stringify(x) + "<br/>");
});
// result:
// {"id":"a","lookup":123}
// {"id":"d","lookup":456}
// {"id":"c","lookup":345}
you can use trackBy:
@Component({
selector:'heroes',
template: `
<table>
<thead>
<th>Name</th>
</thead>
<tbody>
<tr *ngFor="let hero of heroes; trackBy: trackHero" >
<td>{{hero.name}}</td>
</tr>
</tbody>
</table>`})
export class Heroes {
heroes = HEROES;
trackHero(index, hero) {
console.log(hero);
}
}