首页 > 解决方案 > 环内垫表角材料

问题描述

我想制作一个循环来在我的角度材料表中显示一些数据,但我不能这样做,因为我不知道怎么做。

 // <img src=" assets/{{element[col.key][0].position}}.jpg alt="img"> // this way works out of the loop.

ts.文件

  columns = [
    {key: 'position', display ...., config : {isPosition:true}},

  ];

材料表组件

<ng-container *ngFor="let col of columns">

 <ng-container *ngIf="col.config.isPosition">
          <div *ngFor="let element of col.config.isPosition">
             <img src=" assets/{{element[col.key].position}}.jpg alt="img">
         </div> 
 </ng-container>

</ng-container>

标签: angulartypescriptangular-material

解决方案


您不能*ngFor用于角材料表。您必须遵守实施规则。您必须在.ts文件中定义您的数据,如下所示,然后您可以将其绑定到 tr like *matRowDef="let row; columns: displayedColumns;"

这是来自 angular material 官方网站的示例,可在此处获得。

HTML:

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef> No. </th>
    <td mat-cell *matCellDef="let element"> {{element.position}} </td>
  </ng-container>

  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>

  <ng-container matColumnDef="weight">
    <th mat-header-cell *matHeaderCellDef> Weight </th>
    <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
  </ng-container>

  <ng-container matColumnDef="symbol">
    <th mat-header-cell *matHeaderCellDef> Symbol </th>
    <td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>

</table>

TS:

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

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
];

@Component({
  selector: 'table-basic-example',
  styleUrls: ['table-basic-example.css'],
  templateUrl: 'table-basic-example.html',
})
export class TableBasicExample {
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = ELEMENT_DATA;
}

结果: 在此处输入图像描述

为了实现img标签,您可以创建一个包含图像 src 的对象并将其映射到自己的列,然后在 DOM 中使用该对象。


推荐阅读