Angular 4如果条件基于从API
问题描述:
收到的值,我想根据API中的值更改primeng数据表的背景颜色。Angular 4如果条件基于从API
这是我的对象格式部件颜色数组,需要与从API中拉出的派对名称相匹配。
this.partyColours = [{liberal: 'red'},{pc: 'blue'},{ndp: 'ndp'},{green: 'green'}];
这是我的HTML代码:
<p-column field="politicalParty" header="Party" [filter]="true" filterMatchMode="equals"
[style]="background-color: {{partyColours}}">
<ng-template pTemplate="filter" let-col>
<p-dropdown [options]="politicalParties" [style]="{'width':'100%'}"
(onChange)="dt.filter($event.value,col.field,col.filterMatchMode)"
styleClass="ui-column-filter"></p-dropdown>
</ng-template>
</p-column>
正如你可以看到,"background-color: {{partyColours}}"
返回一个错误,我试图找出如何工作的逻辑。
答
更新:
<ng-template let-col let-row="rowData" let-ri="rowIndex" pTemplate="body">
<span #x>{{ setColor(x, row[col.field]) }}{{row[col.field]}}</span>
</ng-template>
setColor(x, data) {
x.parentNode.parentNode.style.background = this.partyColoursMap[data);
}
旧版本:
可以使用以下语法:
<p-column field="politicalParty" header="Party" [filter]="true" class="red"
[style]="{ backgroundColor: partyColoursMap[selectedParty] }" ...>
<ng-template pTemplate="filter" let-col>
<p-dropdown [options]="politicalParties" [(ngModel)]="selectedParty" ...></p-dropdown>
</ng-template>
</p-column>
其中partyColoursMap
对象基于partyColours
阵列计算:
partyColoursMap: any = {};
ngOnInit() {
this.partyColours.forEach(x =>
Object.keys(x).forEach(key => this.partyColoursMap[key] = x[key]));
}
答
<p-column field="politicalParty" header="Party" [filter]="true" filterMatchMode="equals"
[style.backgroundColor]="pickColor(politicalParties.name)">
在组件
pickColor(name: string) {
if (name === 'liberal')
return 'red'
if(name === 'pc')
return 'blue'
// same structure for all parties
}
这是最简单的方法,你也可以去的类路径。显然politicalParties.name需要是正确的......我不知道你的党的对象是什么样子,你可能需要遍历数组或使用* NgFor
是的,我该怎么做? – azmatrix
正如您可以从“[options] =”politicalParties“示例中看到的那样从API获取各方。如果我可以以某种方式将派对名称连接到颜色数组,它应该可以工作 – azmatrix