Angular中如何在所有Action选项隐藏时隐藏菜单触发按钮?
问题根源
你的代码存在两个关键问题:
allOptionsHidden方法没有正确执行hide函数来判断每个action的隐藏状态,而是直接取函数对象的valueOf,无法得到正确的布尔结果- 模板中的
*ngIf条件逻辑颠倒,当前写法会在所有选项隐藏时显示按钮,与需求完全相反
解决方案
1. 修正allOptionsHidden方法
修改方法,接收当前item作为参数,遍历每个action并执行其hide函数(同时处理hide未定义的情况,默认不隐藏):
allOptionsHidden(item: MyEntity): boolean { // 检查所有action是否都需要隐藏 return this.config.actions.every(action => { // 如果action没有hide函数,默认不隐藏(返回false) if (!action.hide) return false; // 执行hide函数,传入当前item获取实际隐藏状态 return action.hide(item); }); }
2. 修正模板中的按钮显示条件
把按钮的*ngIf条件改为!allOptionsHidden(item),确保不是所有选项都隐藏时才显示按钮:
<button mat-icon-button *ngIf="!allOptionsHidden(item)" [matMenuTriggerFor]="actionsMenu" [matMenuTriggerData]="{item: item, config: config}"> <mat-icon>more_vert</mat-icon> </button> <mat-menu #actionsMenu="matMenu"> <ng-template matMenuContent let-item="item"> <div *ngFor="let action of config.actions"> <div *ngIf="!action.hide || !action.hide(item)"> <button mat-menu-item (click)="action.action(item)"> <span>{{action.title}} </span> </button> </div> </div> </ng-template> </mat-menu>
同时建议统一模板内的隐藏判断逻辑,直接使用!action.hide || !action.hide(item),避免依赖额外方法,保持逻辑一致性。
内容的提问来源于stack exchange,提问作者Assustadora de Código
相关产品推荐
相关产品推荐

