在angular2中的ngFor内部调用函数 [英] Call a function inside ngFor in angular2

查看:124
本文介绍了在angular2中的ngFor内部调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我使用的是Angular2,想获取服务器并获取ngFor中每个ID的一些值.

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>

推荐答案

您可以使用自定义指令为每次迭代调用方法:

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'); 
  } 

}

然后可以在* ngFor中使用它来调用组件中的方法:

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);
}

这篇关于在angular2中的ngFor内部调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆