【问题标题】:How to use CSS grid with a dynamic number of columns and rows?如何使用具有动态列数和行数的 CSS 网格?
【发布时间】:2020-02-13 09:54:56
【问题描述】:

我正在尝试在 Angular 中创建一个具有动态列数和行数的表。通过执行以下操作,我发现使用 HTML 表格元素很容易完成:

    <table class="html-table">
      <tr class="headers">
        <th>Name</th>
        <th>Age</th>
        <th>Sex</th>
        <th *ngIf="columns == 4">Species</th>
      </tr>
      <tr>
        <td>Ryan</td>
        <td>30</td>
        <td>M</td>
        <td *ngIf="columns == 4">Human</td>
      </tr>
    </table>

在此示例中,可能有一些按钮可以在 34 之间切换 columns 的值。

我在网上看到的每一个解释都涉及更改 CSS 变量,这似乎是一种完成本应简单的事情的有点老套的方法。有什么方法可以让我指定某个东西应该是 CSS 网格中的新列,而不是必须指定 grid-template-columns 中的列数?

【问题讨论】:

  • 坦率地说,CSS-Grid 并不是table 的理想替代品。使用有效且语义上正确的方法。
  • 这是我推荐使用表格的少数场景之一
  • CSS 变量不是 hacky : developer.mozilla.org/en-US/docs/Web/CSS/… 可能不容易高效使用,但不是 hacky 因为 drafts.csswg.org/css-variables/#using-variables ,只是没有最终确定 ;)
  • 对于 css-grid 你要求的是 grid-auto-columns: auto;连同 grid-auto-flow: column;希望这会有所帮助。
  • @RudyLister 太棒了!那么如何告诉子元素是行还是新列呢?

标签: html css html-table flexbox css-grid


【解决方案1】:

在 Angular 中,您可以使用 ng-repeat 来创建动态表

一个典型的例子是

<table ng-table="tableParams" class="table table-striped">
   <tr ng-repeat="data in datas">
      <td title="Title_Of_First_Variable">{{data.variable1}}</td>
      <td title="Title_Of_Second_Variable">{{data.variable2}}</td>
      <td title="Title_Of_Third_Variable">{{data.variable3}}</td>
      ...
   </tr>
</table>

当然,使用控制器时,您应该将动态数据传递到正确的 $scope,在这种情况下应该是 $scope.datas(通常是一个对象)...可能是这样的,使用 NodeJS:

$http.post('route_of_your_method')
.success(function (result) {
     $scope.datas = result;      
})
.error(function (err) {
     ...
});

我解释得很快,但我希望这就足够了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-06
    • 2017-08-24
    • 2017-09-16
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多