Hello I am using Angular2 and wanted to fetch the server and get some values for each ID I get inside ngFor.
<div *ngFor="let item in items">
<span> here call a function that do something with 'item' and return something new <span>
</div>
Do it in code and assign it to each item and then just use it inside *ngFor . Such function calls from template bindings are discouraged.
While you are not allowed to use *ngIf and *ngFor in the same div (it will gives an error in the runtime) you can nest the *ngIf in the *ngFor to get the desired behavior.
In *ngFor the * is a shorthand for using the new angular template syntax with a template tag, this is also called structural Directive.It is helpful to know that * is just a shorthand to explicitly defining the data bindings on a template tag. Follow this answer to receive notifications.
You can't use multiple *ngFor s in the same element as those are structural directives and angular handles them in a specific way (basically for each structural directive it creates an ng-template element which then holds the directive itself, you can read more about it here: https://angular.io/guide/structural- ...
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With