Hello I am using Angular2 and wanted to fetch the server and get some values for each ID I get inside ngFor.
Doesn't sound very good , however , the simplest way :
<div *ngFor="let item of items">
<span data-dummy="{{myFunction()}}" > here call a function that do something with 'item' and return something new <span>
</div>
Proper way :
@Directive({
selector: '[runDummyFunc]'
})
export class runDummyFunc {
constructor() {}
ngOnInit() {
this.runDummyFunc()
}
}
<div *ngFor="let item in items">
<span [runDummyFunc]="myFunction" > here call a function that do something with 'item' and return something new <span>
</div>
In your class :
myFunction = ():void=>{
console.log('whatever');
}
Better do such function calls on each item in ngOnInit in a subscription, and then they should be displayed with *ngFor after transformation.
and change:
<div *ngFor="let item in items">
to
<div *ngFor="let item of items">
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);
return hero ? hero.id : undefined;
}
}
Not sure if this is what you're asking, but you can pass in the item to a function along with an event variable like this:
<div *ngFor="let item in items">
<span (click)="functionCall($event, item)"> <span>
</div>
And then grab that item in your class like this:
functionCall(event, item): void {
console.log('item clicked:", item)
}
Write an another "ngFor" in between span tag in component.html
<div *ngFor="let item in items">
<span *ngFor="let new of filterItems(item)"> {{new.anyAttribute}} </span>
</div>
in component.ts if you want to filter item
filterItems(item) {
let filterArray:any=[];
return filterArray.filter(x => x.anyAttribute == item.anyAttribute);
}
if you want to return an array in item
filterItems(item){
return item.Array //Array is an array in item
}
You can make use of custom directive to call the method for each iteration:
import { Directive, Output, EventEmitter, Input, SimpleChange} from '@angular/core';
@Directive({
selector: '[onCreate]'
})
export class OnCreate {
@Output() onCreate: EventEmitter<any> = new EventEmitter<any>();
constructor() {}
ngOnInit() {
this.onCreate.emit('dummy');
}
}
and then you can use it in your *ngFor to call the method in your component:
<div *ngFor="let item of items">
<div *ngIf="item" (onCreate)="yourMethod(item)">
</div>
</div>
in Your component you can call this method as:
yourMethod(item){
console.log(item);
}