Andrew Q
Andrew Q

Reputation: 57

Angular material - Menu click event for menu A is also being used for menu B

I'm building a coffee shop app with Angular and Angular Material. I have 3 menus, one for cup size and another two for setting the amount of cream & sugar separately.

The first menu works fine but for some reason, the "click" event of setting the creams number is also occurring for the sugar menu. By this, I mean that if I click one of the sugar options, it will apply it to the creams and change its value but not the sugar one. E.g. I click "3" when I open the sugar menu but instead I will see "Creams: 3" and "Sugars: 0". I'm not sure why it's happening here but the first menu isn't affected at all from there being another menu below it.

Here is a stackblitz link that tried to replicate the issue but for some reason menus from angular material don't work: https://stackblitz.com/edit/angular-ivy-5pgvtm

<div>
    <button mat-button [matMenuTriggerFor]="menu">Size: {{drink.currentSize}}</button>
    <mat-menu #menu="matMenu">
        <button mat-menu-item *ngFor="let size of drink.productOptions" 
        (click)="drinks[i].currentSize = size[0]">{{size[0]}}</button>
        
    </mat-menu>
    <button mat-button (click)="addMenuItemToCart(drink)">Add to cart</button>

    <div *ngIf="drink.type ==='HC' || 'IC'">
        <div>
            <button mat-button [matMenuTriggerFor]="menu">Creams: {{drink.creams}}</button>
            <mat-menu #menu="matMenu">
                <button mat-menu-item *ngFor="let cream of [1,2,3,4]" (click)="drink.creams=cream">{{cream}}</button>    
            </mat-menu>
        </div>
        <div>
            <button mat-button [matMenuTriggerFor]="menu">Sugars: {{drink.sugars}}</button>
            <mat-menu #menu="matMenu">
                <button mat-menu-item *ngFor="let sugar of [1,2,3,4]" (click)="drink.sugars=sugar">{{sugar}}</button>
            </mat-menu>
        </div>
    </div>
</div>

Upvotes: 1

Views: 9347

Answers (1)

digital-pollution
digital-pollution

Reputation: 1074

<button mat-button [matMenuTriggerFor]="menuCustomId">Creams: {{drink.creams}}</button>
<mat-menu #menuCustomId="matMenu">
...

<button mat-button [matMenuTriggerFor]="menuCustomId2">Creams: {{drink.creams}}</button>
<mat-menu #menuCustomId2="matMenu">
...

all your menus have the same id, give them unique id's. you also need to update the triggerFor binding to use the right ID. In your stackblitz example the only issue was the browserAnimations haven't been imported.

Upvotes: 0

Related Questions