javascript - angular 2 - ngFor 动态函数

标签 javascript angular angular2-directives angular2-components

我有一个表格组件,它采用输入 JSON 作为表格格式,并采用另一个 JSON 作为数据。我的问题是,当我的表格使用 *ngFor 呈现时,我该如何调用 cellFunction?

我的表格格式为 JSON:

tblFormat= [
        { headerTxt: 'Order ID', df: 'Order_ID', color: 'blue', cellFunction: 'testME1' },
        { headerTxt: 'Buyer Name', df: 'name', color: 'blue',cellFunction: 'testME2' }
]

我的组件

import { Component, AfterViewInit, ViewChild, Input } from '@angular/core';

@Component({
    selector: 'table-comp',
    template: `<table class="table table-hover">
    <thead>
        <tr>
            <th *ngFor="let h of tableInfo"  [style.color]="h.color">{{h.headerTxt}}</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let d of data">
            <td *ngFor="let c of tableInfo" [style.color]=" how do I? c.cellFunction()">
                {{d[c.df]}}
            </td>
        </tr>
    </tbody>
 </table>`
    inputs: ['data','tableInfo']
})

export class TableComp {
    tableInfo=[];
    data=[];
} 

最佳答案

主要取决于TestME1TestME2的定义位置。如果是TableComp,你可以尝试做:

 <td *ngFor="let c of tblFormat" [style.color]="this[c.cellFunction]()">

如果函数在其他地方定义,您只需将 this 替换为定义它的对象。

例如,您可以拥有一个包含您注入(inject)组件的所有颜色函数的服务:

class TableComp {
    constructor(public colorFunctions: ColorFunctions) {}
}

如果您有这样的服务,您可以:

<td *ngFor="let c of tblFormat" [style.color]="colorFunctions[c.cellFunction]()">

其实,我不知道你到底想做什么!

关于javascript - angular 2 - ngFor 动态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50277380/

相关文章:

angular - 从 fxLayoutGap 行的最后一个元素中删除填充

css - ng2-select 简单的方法来获得漂亮的 CSS

Angular 2 : How to call a method from another component

更改值时,Angular nb-radio(更改)不会触发

angular - 取消选择单选按钮 Angular 2?

javascript - 如何在 Kendo UI Scheduler 上显示自定义事件?

javascript - 使用 jQuery filter() 获取所有匹配的 .val()

html - 如何使用 Angular 2/Typescript 限制输入字段中的特殊字符

javascript - 当客户端浏览器退出时如何终止node.js服务器连接?

javascript - 用 Javascript 中的 anchor 替换纯文本中的电话号码