我了解了如何将简单图像放入单元格中,如下所示
<img [src]="element.imageUrl" />
但我想知道展示星星集合的最佳方式是什么。假设我有一个名为“overallRaiting”的字段,其值为 0 到 5。如果该值为 0,我想不显示星星,如果为 1,则显示 1 颗星,如果为 2,则显示 2 颗星,依此类推。 这是我迄今为止想到的可行的方法,但希望可能有更好的方法。
<ng-container matColumnDef="imageUrl">
<th mat-header-cell *matHeaderCellDef> Image Url </th>
<td mat-cell *matCellDef="let element">
<img *ngIf="element.overallRaiting>=1" [src]="element.imageUrl" />
<img *ngIf="element.overallRaiting>=2" [src]="element.imageUrl" />
<img *ngIf="element.overallRaiting>=3" [src]="element.imageUrl" />
<img *ngIf="element.overallRaiting>=4" [src]="element.imageUrl" />
<img *ngIf="element.overallRaiting>=5" [src]="element.imageUrl" />
</ng-container>
我是否必须为每个 nbr 制作 *ngif 还是更干净、更可重用的方式?
好的,尝试一下
<ng-container matColumnDef="overall_rating">
<th mat-header-cell *matHeaderCellDef> Overall Rating </th>
<td mat-cell *matCellDef="let element">
<ng-container *ngFor="let i of [].constructor(element.overall_rating)">
<img class="star" src="../../assets/images/basic-5-point-gold-star-beveled.jpg" />
</ng-container>
{{element.overall_rating}}
</td>
</ng-container>
这会在文档中产生这个
<td _ngcontent-snv-c2="" class="mat-cell cdk-column-overall_rating mat-column-overall_rating" mat-cell="" role="gridcell"><!--bindings={
"ng-reflect-ng-for-of": "4"
}--><!----><img _ngcontent-snv-c2="" class="star" src="../../assets/images/basic-5-point-gold-star-beveled.jpg"> 4 </td>
最佳答案
您可以使用 *ngFor
来避免使用多个 *ngIf
。
<ng-container matColumnDef="imageUrl">
<th mat-header-cell *matHeaderCellDef> Image Url </th>
<td mat-cell *matCellDef="let element">
<ng-container *ngFor="let i of [].constructor(element.overallRating)">
<img [src]="element.imageUrl" />
</ng-container>
</td>
</ng-container>
还有其他ways您可以使用 *ngFor
重复一个元素,但这看起来更简单。
您还可以抽象出此逻辑并创建一个子组件,该子组件将评级作为输入并显示相应的星数。
<ng-container matColumnDef="imageUrl">
<th mat-header-cell *matHeaderCellDef> Image Url </th>
<td mat-cell *matCellDef="let element">
<app-star-rating [rating]="element.overallRating"><app-star-rating>
</td>
</ng-container>
关于angular - 如何在 Angular Material Table 单元格中显示一张或多张图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57963058/