在表格组件内部显示垫子芯片

时间:2018-10-12 07:14:45

标签: angular angular-material

我在项目中使用table组件。在第四栏中,我使用chips显示玩家姓名,如下图所示: enter image description here

这是我的问题:,如果我在players字符串中添加2个或更多这样的名称:

  players: 'Dwayne Jhonson,Tom cruise' 

两个名称都显示在与上图相同的chip中,但是我希望每个名称都显示在separate chips中。

类似这样的东西:

enter image description here

组件代码: 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="players">
    <th mat-header-cell *matHeaderCellDef> Players </th>
    <td mat-cell *matCellDef="let element"> 
       <mat-chip-list>
              <mat-chip>{{element.players}} </mat-chip>
        </mat-chip-list>
    </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;
  players: string;
}
const ELEMENT_DATA: PeriodicElement[] = [
  {position: 1, name: 'Hydrogen', weight: 1.0079, players: 'Dwayne Jhonson,Tom cruise'},
  {position: 2, name: 'Helium', weight: 4.0026, players: 'Kevin peterson, Brett Lee'},
  {position: 3, name: 'Lithium', weight: 6.941, players: 'Sachin Tendulakar, Yuvraj Sing'},
];

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

这是stackblitz链接。

1 个答案:

答案 0 :(得分:1)

如果可以更改模型,请尝试此操作。

symbol属性声明为string数组:

 export interface PeriodicElement {
  ....  
  symbol: string[];
}

然后类似地更改您的数据:

const ELEMENT_DATA: PeriodicElement[] = [
  {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: ['Dwayne Jhonson','Tom cruise']},
  {position: 2, name: 'Helium', weight: 4.0026, symbol: ['Kevin peterson', 'Brett Lee']},
...
]

最后在视图中,遍历符号元素以创建多个筹码:

  <ng-container matColumnDef="symbol">
    <th mat-header-cell *matHeaderCellDef> Players </th>
    <td mat-cell *matCellDef="let element"> 
       <mat-chip-list>
         <span *ngFor="let symbols of element.symbol">
              <mat-chip>{{symbols}} </mat-chip>
          </span>
          </mat-chip-list>
      </td>
  </ng-container>

Demo

如果不能更改模型 ,则需要创建一个函数,该函数将以symbol属性作为参数,并返回一个string数组,其中strings为由,分割的原始字符串。然后,在视图中,您必须迭代该数组以生成芯片。