如何在Angular的mat-grid网格红色单元格内添加图片图标
解决方案
你可以通过新增判断方法配合模板条件渲染实现红色单元格插入图标的需求,具体修改如下:
1. 修改TypeScript代码
先抽离单元格是否为红色的判断逻辑,避免模板和颜色方法重复计算:
// 新增判断单元格是否需要标红的方法 checkCellIsRed(cell): boolean { const withinA = this.distance >= cell.minDistanceToA && this.distance <= cell.maxDistanceToA && this.distance > 0; const withinB = this.distance2 >= cell.minDistanceToB && this.distance2 <= cell.maxDistanceToB && this.distance2 > 0; return withinA && withinB; } // 原有getCellColor方法直接复用上述判断逻辑即可 getCellColor(cell): string { return this.checkCellIsRed(cell) ? "red" : "green"; }
2. 修改HTML模板
在mat-grid-tile内部增加条件渲染的图标标签:
<mat-grid-list cols="10"> <mat-grid-tile *ngFor="let cell of cells" [style.background]="cell.color" [ngStyle]="{'background-color':getCellColor(cell)}"> {{cell.id}} <!-- 红色单元格显示自定义图标,src替换为你实际的图标路径即可 --> <img *ngIf="checkCellIsRed(cell)" src="assets/你的图标文件路径.png" alt="标识图标" class="cell-icon"> </mat-grid-tile> </mat-grid-list>
3. 增加CSS调整图标样式
可根据需求调整图标的大小、位置,避免和单元格文字重叠:
.cell-icon { width: 18px; height: 18px; position: absolute; right: 3px; top: 3px; }
小提示:如果使用Angular Material自带的图标,只需提前在对应模块导入
MatIconModule,将img标签替换为<mat-icon *ngIf="checkCellIsRed(cell)" class="cell-icon">warning</mat-icon>即可使用内置图标。
内容的提问来源于stack exchange,提问作者WCM
相关产品推荐
相关产品推荐

