Создайте базовую таблицу с развернутой строкой

Я использую Angular версии 6 и хочу либо решение Angular, либо чистое решение html / javascript для таблицы с расширенными строками.

Поэтому, когда вы щелкаете строку, она расширяется.

Примечание: я не хочу использовать угловой материал, jQuery или какие-либо третьи стороны.

Это моя таблица HTML:

  <table class = "ex-table p3">
    <thead class = "ex-table__head">
      <tr class = "ex-table__row">
        <th class = "ex-table__cell">id</th>
        <th class = "ex-table__cell">First Name</th>
      </tr>
    </thead>
    <tbody>
      <tr class = "ex-table__row"  *ngFor = "let item of data">
          <td class = "ex-table__cell">
            {{item.od}}
          </td>
          <td class = "ex-table__cell">
            {{item.firstName}}
          </td>
      </tr>
    </tbody>
  </table>

Я попытался использовать rowspan, colspan и вложенные таблицы, но не смог заставить это работать.

Я не могу сказать, как вы хотите, чтобы это расширилось. Что не так с другим <tr> и использованием *ngIf для переключения его отображения?

Reactgular 30.05.2018 18:45

его динамические данные. Итак, каждая строка отображается, и я хочу щелкнуть tr и развернуть ее. Но это не позволит мне сделать вложенный tr внутри tr

AngularM 30.05.2018 18:48

@cgTag есть идеи, как этого добиться с помощью ngFor?

AngularM 31.05.2018 11:04

@AngularM прежде всего начните с модели данных ex: row model {od: number, firstName: string, children: []}, так что теперь у вас есть подсказка, что вы должны использовать ngIf для детей. чем вам нужно обновить html, чтобы вы не ngFor <tr>, а <ng-content> и внутри него были два <tr>, один для данных и для вложения.

Ervin Llojku 28.08.2018 10:48

А как насчет Bootstrap, или вам не нужен бутстрап?

Dupinder Singh 10.05.2020 16:25
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
5
105
1

Ответы 1

Вы хотите что-то подобное ниже? . строки могут быть расширены. даже всю таблицу можно развернуть сразу.

<html>

<head>
    <script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>

    <script type = "text/javascript">
        function toggle(btnID, eIDs) {
            // Feed the list of ids as a selector
            var theRows = document.querySelectorAll(eIDs);
            // Get the button that triggered this
            var theButton = document.getElementById(btnID);
            // If the button is not expanded...
            console.info(theButton.getAttribute("aria-expanded"))
            if (theButton.getAttribute("aria-expanded") == "false") {
                // Loop through the rows and show them
                for (var i = 0; i < theRows.length; i++) {
                    theRows[i].classList.add("shown");
                    theRows[i].classList.remove("hidden");
                }
                // Now set the button to expanded
                theButton.setAttribute("aria-expanded", "true");
                // Otherwise button is not expanded...
            } else {
                // Loop through the rows and hide them
                for (var i = 0; i < theRows.length; i++) {
                    theRows[i].classList.add("hidden");
                    theRows[i].classList.remove("shown");
                }
                // Now set the button to collapsed
                theButton.setAttribute("aria-expanded", "false");
            }
        }

        function toggle1(btnID, eIDs) {
            // Feed the list of ids as a selector
            var theRows = document.querySelectorAll(eIDs);
            // Get the button that triggered this
            var theButton = document.getElementById(btnID);
            // If the button is not expanded...
            if (theButton.getAttribute("aria-expanded") == "false") {
                // Loop through the rows and show them
                for (var i = 0; i < theRows.length; i++) {
                    theRows[i].classList.add("shown");
                    theRows[i].classList.remove("hidden");
                }
                // Now set the button to expanded
                theButton.setAttribute("aria-expanded", "true");
                document.getElementById("btnMSb1").setAttribute("aria-expanded", "true");
                document.getElementById("btnMSb2").setAttribute("aria-expanded", "true");
                document.getElementById("btnMSb3").setAttribute("aria-expanded", "true");
                // Otherwise button is not expanded...
            } else {
                // Loop through the rows and hide them
                for (var i = 0; i < theRows.length; i++) {
                    theRows[i].classList.add("hidden");
                    theRows[i].classList.remove("shown");
                }
                // Now set the button to collapsed
                theButton.setAttribute("aria-expanded", "false");
                document.getElementById("btnMSb1").setAttribute("aria-expanded", "false");
                document.getElementById("btnMSb2").setAttribute("aria-expanded", "false");
                document.getElementById("btnMSb3").setAttribute("aria-expanded", "false");
            }
        }
    </script>
</head>
<style>
    body {
        font-family: "Segoe UI", -apple-system, BlinkMacSystemFont, Roboto,
        Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
        line-height: 1.4;
        background: #fefefe;
        color: #333;
        margin: 0 1em;
    }

    table {
        width: 100%;
        margin: 1em 0;
        border-collapse: collapse;
    }

    caption {
        text-align: left;
        font-style: italic;
        padding: 0.25em 0.5em 0.5em 0.5em;
    }

    th,
    td {
        padding: 0.25em 0.5em 0.25em 1em;
        vertical-align: text-top;
        text-align: left;
        text-indent: -0.5em;
    }

    th {
        vertical-align: bottom;
        background-color: rgba(0, 0, 0, 0.75);
        color: #fff;
        font-weight: bold;
    }

    .process {
        margin-top: 35px;
        display: inline-block;
        width: 10%;
        padding: 5px;
        border-top: 3px solid black;
        border-bottom: 3px solid black;
        color: #fff;
        font-style: normal;
        font-weight: bold;
    }

    .row td:nth-of-type(2),
    .cell td:nth-of-type(3) {
        font-style: italic;
    }

    .row th:nth-of-type(3),
    .row td:nth-of-type(3),
    .cell th:nth-of-type(4),
    .cell td:nth-of-type(4) {
        text-align: right;
    }

    td[colspan] {
        background-color: #f5f5f5;
        color: #000;
        font-weight: normal;
        font-style: italic;
        padding: 0;
        text-indent: 0;
    }

    tr.shown,
    tr.hidden {
        display: table-row;
    }

    tr.hidden {
        display: none;
    }

    .row button {
        background-color: transparent;
        border: .1em solid transparent;
        font: inherit;
        padding: 0.25em 0.5em 0.25em .25em;
        width: 100%;
        text-align: left;
    }

    .row button:focus,
    .row button:hover {
        background-color: #ddd;
        outline: .2em solid #00f;
    }

    .row button svg {
        width: .8em;
        height: .8em;
        margin: 0 0 -.05em 0;
        fill: #66f;
        transition: transform 0.25s ease-in;
        transform-origin: center 45%;
    }

    .row button:hover svg,
    .row button:focus svg {
        fill: #00c;
    }

    /* Lean on programmatic state for styling */

    .row button[aria-expanded = "true"] svg {
        transform: rotate(180deg);
    }

    .cell button {
        font-size: 60%;
        color: #000;
        background-color: #00f;
        padding: 0.3em 0.2em 0 0.2em;
        border: 0.2em solid #00f;
        border-radius: 50%;
        line-height: 1;
        text-align: center;
        text-indent: 0;
        transform: rotate(270deg);
    }

    .cell button svg {
        width: 1.25em;
        height: 1.25em;
        fill: #fff;
        transition: transform 0.25s ease-in;
        transform-origin: center 45%;
    }

    .cell button:hover,
    .cell button:focus {
        background-color: #fff;
        outline: none;
    }

    .cell button:hover svg,
    .cell button:focus svg {
        fill: #00f;
    }

    /* Lean on programmatic state for styling */

    .cell button[aria-expanded = "true"] svg {
        transform: rotate(90deg);
    }

    /* Proven method to visually hide something but */

    /* still make it available to assistive technology */

    .visually-hidden {
        position: absolute;
        top: auto;
        overflow: hidden;
        clip: rect(1px 1px 1px 1px);
        /* IE 6/7 */
        clip: rect(1px, 1px, 1px, 1px);
        width: 1px;
        height: 1px;
        white-space: nowrap;
    }
</style>

<table class = "cell">
    <caption>Dashboard</caption>
    <thead>
        <tr>
            <th><button type = "button" id = "btnMSb" aria-expanded = "false" onclick = "toggle1(this.id,'#MS01b,#MS02b,#MS03b');" aria-controls = "MS01b MS02b MS03b" aria-label = "3 more from" aria-labelledby = "btnMSb lblMSb">
          <svg xmlns = "\http://www.w3.org/2000/svg&quot;" viewBox = "0 0 80 80" focusable = "false"><path d = "M70.3 13.8L40 66.3 9.7 13.8z"></path></svg>    
        </button></th>
            <th>Batch</th>
            <th>Status</th>
            <th>Start</th>
            <th>End</th>
            <th>agreed</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <button type = "button" id = "btnMSb1" aria-expanded = "false" onclick = "toggle(this.id,'#MS01b');" aria-controls = "MS01b" aria-label = "3 more from" aria-labelledby = "btnMSb1 lblMSb1">
          <svg xmlns = "\http://www.w3.org/2000/svg&quot;" viewBox = "0 0 80 80" focusable = "false"><path d = "M70.3 13.8L40 66.3 9.7 13.8z"></path></svg>    
        </button>
            </td>
            <td>Batch1</td>
            <td>Green</td>
            <td>10AM</td>
            <td>11AM</td>
            <td>11:30AM</td>
        </tr>
        <tr id = "MS01b" class = "hidden">
            <td></td>
            <td colspan = "5">
                <div style = "vertical-align: middle; text-align: center;height: 100px;">
                    <div class='process' style = "border-right-style: none;border-left: 3px solid black; background-color: #16a085">Step1</div>
                    <div class='process' style = "color:#222; margin-left:-5px ; border-right-style: none;border-left-style: none; background-color: #F1A9A9">Step2</div>
                    <div class='process' style = "color:#222; margin-left:-5px ; border-right-style: none;border-left-style: none; background-color: #E4FFAE">Step3</div>
                    <div class='process' style = "color:#222; margin-left:-5px ; border-right-style: none;border-left-style: none; background-color: #BFC6B9">Step4</div>
                    <div class='process' style = "color:#222; margin-left:-5px ; border-right-style: none;border-left-style: none; background-color: #87FEF8">Step5</div>
                    <div class='process' style = "color:#222; margin-left:-5px ; border-right: 3px solid black;border-left-style: none; background-color: #FF9A9E">Step6</div>
                </div>
            </td>

        </tr>
        <tr>
            <td>
                <button type = "button" id = "btnMSb2" aria-expanded = "false" onclick = "toggle(this.id,'#MS02b');" aria-controls = "MS02b" aria-label = "3 more from" aria-labelledby = "btnMSb2 lblMSb2">
          <svg xmlns = "\http://www.w3.org/2000/svg&quot;" viewBox = "0 0 80 80" focusable = "false"><path d = "M70.3 13.8L40 66.3 9.7 13.8z"></path></svg>    
        </button>
            </td>
            <td>Batch2</td>
            <td>Green</td>
            <td>2AM</td>
            <td>4AM</td>
            <td>5AM</td>
        </tr>
        <tr id = "MS02b" class = "hidden">
            <td></td>
            <td colspan = "5">
                <div style = "vertical-align: middle; text-align: center;height: 100px;">
                    <div class='process' style = "border-right-style: none;border-left: 3px solid black; background-color: #16a085">Step1</div>
                    <div class='process' style = "margin-left:-5px ; border-right-style: none;border-left-style: none; background-color: #DB2929">Step2</div>
                    <div class='process' style = "margin-left:-5px ; border-right-style: none;border-left-style: none; background-color: #C0FF3E">Step3</div>
                    <div class='process' style = "margin-left:-5px ; border-right-style: none;border-left-style: none; background-color: #5A6351">Step4</div>
                    <div class='process' style = "margin-left:-5px ; border-right-style: none;border-left-style: none; background-color: #01C5BB">Step5</div>
                    <div class='process' style = "color:#222; margin-left:-5px ; border-right: 3px solid black;border-left-style: none; background-color: #FF9A9E">Step6</div>
                </div>
            </td>

        </tr>
        <tr>
            <td>
                <button type = "button" id = "btnMSb3" aria-expanded = "false" onclick = "toggle(this.id,'#MS03b');" aria-controls = "MS03b" aria-label = "3 more from" aria-labelledby = "btnMSb3 lblMSb3">
          <svg xmlns = "\http://www.w3.org/2000/svg&quot;" viewBox = "0 0 80 80" focusable = "false"><path d = "M70.3 13.8L40 66.3 9.7 13.8z"></path></svg>    
        </button>
            </td>
            <td>Batch3</td>
            <td>Amber</td>
            <td>10AM</td>
            <td>11AM</td>
            <td>10:30AM</td>
        </tr>
        <tr id = "MS03b" class = "hidden">
            <td></td>
            <td colspan = "5">
                <div style = "vertical-align: middle; text-align: center;height: 100px;">
                    <div class='process' style = "border-right-style: none;border-left: 3px solid black; background-color: #1abc9c">Step1</div>
                    <div class='process' style = "margin-left:-5px ; border-right-style: none;border-left-style: none; background-color: #3498db">Step2</div>
                    <div class='process' style = "margin-left:-5px ; border-right-style: none;border-left-style: none; background-color: #34495e">Step3</div>
                    <div class='process' style = "margin-left:-5px ; border-right-style: none;border-left-style: none; background-color: #2ecc71">Step4</div>
                    <div class='process' style = "margin-left:-5px ; border-right-style: none;border-left-style: none; background-color: #9b59b6">Step5</div>
                    <div class='process' style = "margin-left:-5px ; border-right: 3px solid black;border-left-style: none; background-color: #e74c3c">Step6</div>
                </div>
            </td>

        </tr>
    </tbody>
</table>


</html>

Другие вопросы по теме