基于条件禁用按钮:Angular中按bought字段控制编辑按钮显隐
根据bought字段状态控制编辑按钮的Angular实现方案
嘿,我来帮你搞定这个需求!你需要基于bought这个布尔类型字段的值,控制编辑按钮的显示/禁用逻辑——当bought为true时禁用(或隐藏)按钮,为false时正常显示可点击的按钮。结合你现有的代码,这里有两种实用的实现方式:
方案1:直接隐藏编辑按钮(当bought为true时不渲染)
这种方式会在bought为true时完全不渲染按钮所在的单元格,适合不需要展示禁用状态按钮的场景。你只需要修改按钮所在<td>的*ngIf条件,加入对baker.bought的判断:
<div *ngIf="isbaker"> <div class="table-responsive"> <table class="table"> <thead class="table_header"> <tr> <th>Customer</th> <th>Name</th> <th>Bought</th> </tr> </thead> <tbody> <tr *ngFor="let baker of shop;"> <td>{{ baker.customer }}</td> <td>{{ baker.name}}</td> <td>{{ baker.bought}}</td> <!-- 修改这里的*ngIf,加入!baker.bought判断 --> <td *ngIf="isButton && !baker.bought"> <button mat-icon-button matTooltip="Edit" class="iconbutton" (click)="isbakerEdit(baker)" color="primary"> <mat-icon style="color: gray;" aria-label="Edit">edit</mat-icon> </button> </td> </tr> </tbody> </table> </div> </div>
解释:!baker.bought表示仅当bought字段为false时,才渲染这个包含编辑按钮的单元格,完全隐藏不需要的按钮。
方案2:禁用按钮但保留显示(当bought为true时不可点击)
如果你希望按钮依然显示,但处于不可点击的禁用状态,可以保留原来的<td>渲染逻辑,给按钮添加[disabled]属性绑定:
<div *ngIf="isbaker"> <div class="table-responsive"> <table class="table"> <thead class="table_header"> <tr> <th>Customer</th> <th>Name</th> <th>Bought</th> </tr> </thead> <tbody> <tr *ngFor="let baker of shop;"> <td>{{ baker.customer }}</td> <td>{{ baker.name}}</td> <td>{{ baker.bought}}</td> <td *ngIf="isButton"> <!-- 添加[disabled]绑定到baker.bought,同时可以调整图标样式 --> <button mat-icon-button matTooltip="Edit" class="iconbutton" (click)="isbakerEdit(baker)" color="primary" [disabled]="baker.bought"> <mat-icon [style.color]="baker.bought ? 'lightgray' : 'gray'" aria-label="Edit">edit</mat-icon> </button> </td> </tr> </tbody> </table> </div> </div>
解释:
[disabled]="baker.bought"会在bought为true时禁用按钮,Angular Material的按钮会自动应用禁用状态的样式(比如透明度降低)- 额外添加的
[style.color]绑定可以根据bought状态调整图标颜色,让禁用状态更直观
你可以根据产品需求选择其中一种方案,两种都能完美实现你要的逻辑~
内容的提问来源于stack exchange,提问作者Expert Labs
相关产品推荐
相关产品推荐

