【问题标题】:Angular (v. 11.2.4) - Angular Material - Insert a component inside a dynamic & server-side mat-table's mat-cellAngular (v. 11.2.4) - Angular Material - 在动态和服务器端 mat-table 的 mat-cell 中插入组件
【发布时间】:2021-06-10 14:33:27
【问题描述】:

我花了一些时间弄清楚如何使下面的场景工作,但没有成功。也许我很幸运,你们中的某个人可以帮助我:)

问题/问题

如何将组件(无论是按钮、mat-chip 还是其他......)添加到动态 mat-table 单元格中?我已经阅读了https://angular.io/guide/dynamic-component-loader,但我无法使用它。

场景

我有使用 Angular 11.2.4 和 Angular Material 11.2.3 的项目。在这个项目中,我构建了一个在许多页面中使用的动态 mat-table 组件。工作正常的事情,直到...我不得不在单元格内插入一个垫芯片(或 >),但我无法做到。

表格组件 HTML

<div class="table-wrapper">
    <table mat-table[dataSource]="config.dataSource">
      <ng-container *ngFor="let col of config.columns">
        <ng-container [matColumnDef]="col.key">
          <th mat-header-cell *matHeaderCellDef mat-sort-header>{{ col.label }}</th>

          <ng-container *ngIf="col.render">
            <td mat-cell *matCellDef="let row">
              <!-- THIS DOESN'T WORK: IT ONLY ADD RAW HTML -->
              <div [innerHTML]="col.render(row, col.key) | safeHtmlPipe"></div>
            </td>
          </ng-container>

          <ng-container *ngIf="!col.render">
            <td mat-cell *matCellDef="let row" [innerHTML]="row[col.key]"></td>
          </ng-container>

        </ng-container>
      </ng-container>

      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
      <ng-container *ngIf="showFilters">
        <tr mat-footer-row *matFooterRowDef="displayedColumns"></tr>
      </ng-container>
    </table>
</div>

表格组件 TS

...
...

    this.tableConfig = {
      dataSource: new TableDataSource(this.myService), // a configurable TableDataSource˙
      pageSizeOptions: [5, 10, 25, 100],
      selectable: false,
      columns: [
        ...,
        {
          key: 'createdBy',
          label: 'Created by',
          sortable: false,
          visible: true,
          render: (row: any, colKey: string): string => {
            const colVal = row[colKey];
            if (colVal) {
              // THIS DOES NOT WORK. IT ONLY PRINT SOME HTML WITHOUT THE "mat-raised-button" DIRECTIVE EFFECTS
              return `<a [routerLink]="'./' + ${row._id}" mat-raised-button color="primary">${colVal.firstName} ${colVal.lastName}</a>`;
            }
            return '';
          },
        },
      ],
      refresh$: new BehaviorSubject<boolean>(false),
    };
...
...

【问题讨论】:

    标签: angular angular-material2 mat-table


    【解决方案1】:

    这样的注入使它只是一个普通的 DOM - 它在应用程序控制之外。指令在这种注入的标记中不起作用。

    不是注入标记,而是将其放入组件代码中,并根据行数据有条件地显示所需的内容

    使用组件工厂有助于根据数据动态选择要使用的组件。因此,不要使用 html 作为行数据,而是使用某种触发器/指示器 - 标志或枚举

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-19
      • 2018-03-25
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 2019-10-10
      • 1970-01-01
      相关资源
      最近更新 更多