Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function inside ngFor in angular2

Tags:

angular

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>
like image 331
elhoucine Avatar asked Aug 05 '16 11:08

elhoucine


People also ask

Can I call function in ngFor?

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.

Can I use ngIf inside ngFor?

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.

What does * mean in ngFor?

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.

Can we use two ngFor in angular?

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- ...


1 Answers

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);
}
like image 139
Bhushan Gadekar Avatar answered Sep 20 '22 11:09

Bhushan Gadekar