Как заполнить данные из json, содержащие значения, разделенные запятыми, в таблицу в angular 8 - PullRequest
0 голосов
/ 01 апреля 2020

У меня есть json, который содержит имя столбца 'status', имеющее несколько значений через запятую. Я уже заполнил этот 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);
    }
}

Ответы [ 2 ]

0 голосов
/ 01 апреля 2020

Я добавил ответ, я решил его, и это то, что я хотел сделать. Вот демонстрационный URL

https://stackblitz.com/edit/angular-o6epjq?file=src%2Fapp%2Fapp.component.ts

home.comoponent. 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 [innerHtml]="getTreatment(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() {
    /* First data */
    this.statusdata1 = [{"vehicle_number":1,"status":"red,green"},{"vehicle_number":2,"status":"yellow,red"}];
    console.log(this.statusdata1);
  }
  getTreatment(data) {
    let str = '<div class="demooutput">'
    let arr = data.split(',');
    if (arr.length > 0) {
      for (let i = 0; i < arr.length; i++) {
        str += '<span class="' + arr[i] + '"><img src="/app/animate/' + arr[i] +  '.png"/></span>'
      }
    }
    str += '</div>'
    return str
  }
}
0 голосов
/ 01 апреля 2020

Рабочий пример Вы можете отправить объект с css атрибутами в 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}"
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...