Description
Feature Description
Very often we find the need to have a menu, where their submenus are conditional. That is, they may or may not exist, base on a condition.
Ideally, the following should work:
<button mat-menu-item [matMenuTriggerFor]="myCondition ? subMenu : null">{{ name }}</button>
Current Workaround
However, since matMenuTriggerFor cannot be null, the above code does not compile. The current solution is duplicating code with *ngIf
:
<button mat-menu-item *ngIf="myCondition" [matMenuTriggerFor]="subMenu">{{ name }}</button>
<button mat-menu-item *ngIf="!myCondition">{{ name }}</button>
Why This is Needed
At first sight, it doesn't look that terrible, but as we start to add other attributes (classes, i18n suff, and other directives), and as the button content also becomes richer (with icons and internationalized text). The code duplication is hard to maintain and can easily introduce bugs in our app.
For example, for the following code:
<button mat-menu-item class="myclass1 myclass2" (onClick)="doSomething() [matMenuTriggerFor]="subMenu">
<mat-icon>check</mat-icon>
<span class="myClass3">{{ name }}</span>
</button>
with the current workaround, the code grows to:
<button mat-menu-item *ngIf="myCondition" class="myclass1 myclass2" i18n="@@buttonDesc" (onClick)="doSomething() [matMenuTriggerFor]="subMenu">
<mat-icon>check</mat-icon>
<span class="myClass3" i18n="@@buttonDesc">{{ name }}</span>
</button>
<button mat-menu-item *ngIf="!myCondition" class="myclass1 myclass2" (onClick)="doSomething()>
<mat-icon>check</mat-icon>
<span class="myClass3" i18n="@@buttonDesc">{{ name }}</span>
</button>
with this proposal, the code would only need to be modified slightly:
<button mat-menu-item class="myclass1 myclass2" (onClick)="doSomething() [matMenuTriggerFor]="myCondition ? subMenu : null">
<mat-icon>check</mat-icon>
<span class="myClass3" i18n="@@buttonDesc">{{ name }}</span>
</button>
Note: Creating a bogus empty submenu does not work as a workaround.
Use Case
Very often I find the need to have a menu, where their submenus are conditional. That is, they may or may not exist, base on a condition.