Angular 4如果条件基于从API

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}}"返回一个错误,我试图找出如何工作的逻辑。

+0

是的,我该怎么做? – azmatrix

+0

正如您可以从“[options] =”politicalParties“示例中看到的那样从API获取各方。如果我可以以某种方式将派对名称连接到颜色数组,它应该可以工作 – azmatrix

更新:

the issue

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

Plunker Example

旧版本:

可以使用以下语法:

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

Stackblitz Example

+0

谢谢,但你stackblitze例如出现空在其浏览器 – azmatrix

+0

试图重新打开它 – yurzui

+0

只是做,没有去 – azmatrix

<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

+0

嗨,谢谢,这是我的对象在组件中的样子:'this.partyColours = [{parties:[liberal':'red'}, {pc:'blue'}, {ndp:'ndp'}, {green:'green'} ]}] ;' – azmatrix

+0

@azmatrix我的意思是您从API中抽取的实际派对信息,用于填充组件。 – deek