簡體   English   中英

我該如何從Typescript文件中獲取有角度的背景顏色並將其綁定到我的html頁面?

[英]How do I get the background color from typescript file in angular and bind it to my html page?

我有一個正在用打字稿填充的數組,並且基於該數組中的值,我想為div設置不同的背景顏色,但是它不起作用。 我究竟做錯了什么?

我嘗試使用[style.backgroundColor] =“ statusColor [i]”設置背景。 statusColor是在我的打字稿中聲明的數組。 如果我嘗試不使用數組將其綁定到單個對象,則它可以正常工作,如下所示:[style.backgroundColor] =“ statusColor”。 這是我得到的錯誤:無法讀取未定義的屬性“ 0”

這是代碼:這是json對象的接口:

export interface IComplaint {
    id: string;
    description: string
    status: string
}

這是我主要組件的打字稿:

public complaints = {} as IComplaint[];        
public statusColor: string[];

在數組中填充投訴后,我使用此功能設置顏色:

for (let i=0; i<this.complaints.length; i++) {
        if (this.complaints[i].status === "Reported")
          this.statusColor[i] = 'red';
        else if (this.complaints[i].status === "Resolved")
          this.statusColor[i] = 'green';
        else if (this.complaints[i].status === "In progress")
          this.statusColor[i] = 'yellow';
        console.log(this.statusColor[i]);
    }       

這是HTML代碼:

<mat-card class="card" *ngFor="let complaint of complaints; let i = index">
<div class="status" [style.backgroundColor]="statusColor[i]">
                        {{ complaint.status }}
                </div>
</mat-card>

<div class="status" [style.backgroundColor]="statusColor[i]">
                            {{ complaint.status }}
                    </div>  

我希望背景顏色根據狀態改變。

嘗試ngStyle如下

[ngStyle]="{'background-color': statusColor[i]}

我認為樣式綁定應為: [style.background-color]="statusColor[i]"

如果您想改善代碼,建議您使用管道進行處理。 Pipe確實也是性能友好的。

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'complaintBgColourPipe'
})
export class ComplaintBgColourPipe implements PipeTransform {
  transform(value: string): string {
    switch (value) {
      case 'Reported': {
        return 'red';
      }

      case 'Resolved': {
        return 'green';
      }

      case 'In progress': {
        return 'yellow';
      }

      default: {
        return '';
      }
    }
  }
}

由於您要遍歷所有投訴數組,因此您可以傳遞狀態並將其傳遞給其他人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM