【问题标题】:Complex Tables in Angular (How to create dynamic)Angular 中的复杂表(如何创建动态表)
【发布时间】:2021-01-18 16:58:14
【问题描述】:

在我当前的项目中,我们必须像您在此处看到的那样显示复杂的表格:https://medium.muz.li/complex-tables-356826d11861(或参见image)。

单元格非常动态,所有信息都来自 API。我们有大约 25 个不同的表,具有相同的功能和行为。现在的解决方案是每个表的组件。我发现这是没有办法的方法,因为这不是非常动态的,而且组件的代码库可能会有所不同,因此我们将难以添加新功能、更改和解决整体表的错误。

据我所知,要在 UI 方面解决这个问题,我正在考虑最好的方法,即基本建筑应该是什么样子。就像我们可以为每个包含行的表格创建一个数组,它将单元格作为对象保存,这些对象包含有关每个单元格的所有信息(可编辑、样式、内容类型、工具提示...)。

优点:动态、一个代码库适用于所有(即将推出的)表格、更快地实现功能和更改、易于操作表格(过滤、搜索、排序、删除/添加行)。

你有什么建议?

【问题讨论】:

  • 你只想使用 angular material 或 ag-grid 之类的库

标签: arrays json angular html-table javascript-objects


【解决方案1】:

扩展 Jeremy 的答案,您可以实施

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

export class Table {
  constructor(
    public title: string,
    public columns: string[],
    public rows: Row[]
  ) {}
}

export class Row {
  constructor(public cells: Cell[]) {}
}

export type CellValue = string | number | boolean;

export class Cell {
  constructor(public value: CellValue) {}

  isText(): boolean {
    return typeof this.value === "string";
  }

  isNumber(): boolean {
    return typeof this.value === "number";
  }

  isBoolean(): boolean {
    return typeof this.value === "boolean";
  }
}

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  title = "CodeSandbox";
  table: Table;

  constructor() {
    this.table = new Table(
      "Table name",
      ["Country", "State", "Population", "Northern"],
      [
        new Row([new Cell("AR"), new Cell("BSAS"), new Cell(44490000), new Cell(false)]),
        new Row([new Cell("US"), new Cell("CA"), new Cell(328000000), new Cell(true)])
      ]
    );
  }
}

并让模板类似于以下内容:

<table>
  <tr>
    <th *ngFor="let col of table.columns">{{col}}</th>
  </tr>
  <tr *ngFor="let row of table.rows">
    <td *ngFor="let cell of row.cells">
      <input type="text" *ngIf="cell.isText()" [(ngModel)]="cell.value" />
      <input type="number" *ngIf="cell.isNumber()" [(ngModel)]="cell.value" />
      <input
        type="checkbox"
        *ngIf="cell.isBoolean()"
        [(ngModel)]="cell.value"
      />
    </td>
  </tr>
</table>

由于[(ngModel)],这些值将在您编写输入时自动填充。希望它可以帮助你。我创建了一个示例here,以防您需要此代码。

【讨论】:

  • 谢谢,看起来不错。非常感谢您的样品!
【解决方案2】:

你的方法完全没问题,而且肯定是要走的路。 如果您想更进一步,您可以为每种类型的单元格创建组件: TextCell、TextfieldCell、SelectCell等...

甚至进一步动态加载您的组件 看看ComponentFactoryResolver 然后在您的数据单元格对象中,添加一个包含组件名称的字段。 虽然这不是最容易做到的,但在可维护性方面会有好处

【讨论】:

  • 非常感谢!动态加载组件听起来很棒。
猜你喜欢
  • 1970-01-01
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-26
  • 2011-07-18
  • 1970-01-01
  • 2019-12-11
相关资源
最近更新 更多