gpt4 book ai didi

javascript - angular 2 - ngFor 动态函数

转载 作者:行者123 更新时间:2023-11-30 06:50:53 26 4
gpt4 key购买 nike

我有一个表格组件,它采用输入 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com