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

Я использую данные json для заполнения таблицы. Здесь мой div внутри td создан динамически. Здесь мне нужно показать только первое значение столбца 'status' во втором td каждой строки (теперь показывает все значения). При наведении этого первого значения мне нужно показать все значения в небольшом интервале. Вот код ниже. Я также создал демо здесь https://stackblitz.com/edit/angular-o6epjq?file=src%2Fapp%2Fapp.component.ts

app.component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
 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
  }
}

app.component. html

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>
<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>

1 Ответ

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

Я думаю, это то, что вы ищете: я поместил стиль в app.component.html, чтобы продемонстрировать его в основном. Вы можете подумать о том, чтобы иметь отдельный компонент для него.

An также произвел небольшой рефакторинг.

Ссылка для всплывающей подсказки: https://www.w3schools.com/css/css_tooltip.asp

app.component. html:

<style>
    .tooltip {
        position: relative;
        display: inline-block;
        border-bottom: 1px dotted black;
    }

    .tooltip .tooltip-content {
        visibility: hidden;
        width: 120px;
        background-color: black;
        color: #fff;
        text-align: center;
        border-radius: 6px;
        padding: 5px 0;

        /* Position the tooltip */
        position: absolute;
        z-index: 1;
    }

    .tooltip:hover .tooltip-content {
        visibility: visible;
    }
</style>

<div>
    <table>
        <tr *ngFor="let x of statusdata1;">
            <td style="border:1px solid"><span>{{x.vehicle_number}}</span></td>
            <td style="border:1px solid">
                <div *ngIf="x.statusAvailable" class="tooltip">
                    {{x.statusUrls[0]}}
                    <span class="tooltip-content">
                        <span *ngFor="let status of x.statusUrls">
                            <img src="{{status}}" />
                        </span>
                    </span>
                </div>
            </td>
        </tr>
    </table>
</div>

app.component.ts

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

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    imageSource: any;
    statusdata1: any;
    customData: any;

    ngOnInit() {
        /* First data */
        const jsonData = [{ "vehicle_number": 1, "status": "red,green" },
        { "vehicle_number": 2, "status": "yellow,red" }];

        this.statusdata1 = this.createCustom(jsonData);
    }

    createCustom(data) {
        return data.map(row => {
            const statusAvailable = typeof row.status === 'string';
            const statusUrls = statusAvailable
                ? row.status.split(',').map(s => this.generateUrl(s))
                : [];

            return {
                ...row,
                statusAvailable,
                primaryStatusUrl: statusAvailable ? statusUrls[0] : undefined,
                statusUrls
            }
        });
    }

    generateUrl(status) {
        return `/app/animate/${status}.png`
    }

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...