首页 > 解决方案 > 如何将包含逗号分隔值的json中的数据填充到角度8的表中

问题描述

我有一个 json,其中包含一个具有多个逗号分隔值的列名“状态”。我已经将该 json 填充到我的表中,但这里的问题是我需要将与来自 json 的背景颜色相同的背景颜色放入 span。我没有到这里怎么做。任何人都可以请帮助我。这是下面的代码

home.component.html

<div>
    <table>
        <tr *ngFor="let x of statusdata1;">
            <td style="border:1px solid"><span>{{x.vehicle_number}}</span></td>
            <td style="border:1px solid"><span style="background:{{x.status}}">{{x.status}}</span></td>
        </tr>
    </table>
</div>

home.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {
    imageSource :any;
    statusdata1: any;

    constructor() {}

    ngOnInit() {
        this.statusdata1 = [{"vehicle_number":1,"status":"red,green"},{"vehicle_number":2,"status":"yellow,red"}];
        console.log(this.statusdata1);
    }
}

标签: htmlangulartypescript

解决方案


工作示例您可以将具有 css 属性的 obj 发送到 ngStyle

TS

 data=  [
  {
    "vehicle_number":1,
    "status":"red,green"
    },{
      "vehicle_number":2,
      "status":"yellow,red"
  }];;

  getColor(value) {
   var colors = value.split(',');
    return {
    'background-color': colors[0],
    'color': colors[1]
  };
 }

HTML

<tr *ngFor="let x of data;">
        <td style="border:1px solid; width:80px" [ngStyle]="getColor(x.status)"><span>{{x.vehicle_number}}</span></td>
        <td style="border:1px solid; width:80px" [ngStyle]="getColor(x.status)">{{x.status}}</td>
</tr>

getColor 将返回 ngStyle

[ngStyle]="{'background-color': yellow, 'color': red}"

推荐阅读