Search code examples
angularpopupmenuangular-cdk

Does Angular's cdkMenu not work with ngModel or forms? The position of the template are no longer next to the button


I would like to create a menu bar for the tipTap text editor. The menu's popovers with heading selection, text color selection etc. work very well, because there are only buttons in the menu. Now i want to add another menu item that opens two inputs to enter one link and a placeholder text. the moment i open the menu, the menu does not appear under the button like the other popUps. It appears on the top right edge. i have used ngModel or form for the inputs. when i delete the ngModel or form. it appears under the menu icon as i expected. i think that the directives ngModel or forms do not work together with the cdkMenue. is this true? the popup closing functionality is also broken.

Here is my html:

 <div cdkMenuBar> 
... menuItems ...
<div class='separator'></div>
  <!-- text link -->
  <button
    cdkMenuItem
    type='button'
    class='button'
    title='Platzhalter Link'
    [cdkMenuTriggerFor]='linkMenu'
  >
    <mat-icon class='small'>link</mat-icon>
  </button>
  <!-- link menu -->
  <ng-template #linkMenu>
    <div class='r-color-menu' cdkMenu>
      <form formGroupName='linkPlaceholderForm' (ngSubmit)='onSubmit()'>
        <input type='text' formControlName='link'
               [placeholder]="'link...'"
        />
        <input
          type='text' formControlName='placeholder'
          [placeholder]="'placeholder...'"
        />

        <button (click)='setLink()'>
          setLink
        </button>
        <button (click)='unsetLink()'>
          unsetLink
        </button>
      </form>
    </div>
  </ng-template>

  <div class='separator'></div>

... menuItems ...
</div>

The red container is the one I created with the input and the green one is the one with the buttons in it. Actually, my red container should look exactly like the green one.

The red container is the one I created with the input and the green one is the one with the buttons in it. Actually, my red container should look exactly like the green one.

how can i create the menu?


Solution

  • For what it's worth, when I ran into something similar when using cdkMenu, the issue was that I had absolute positioning on the menu element. Removing that from my CSS fixed the issue. Your Stackblitz doesn't have any positioning on the menu element, so perhaps you ran into the same issue as I had.

    In case it's relevant, addressing another couple of issues with your Stackblitz fixes some of the behavior, namely:

    1. You have two templates with the same templateRef.
    2. The documentation for CDK Menu has the templates outside of the element containing the menu bar.
    3. You have a formGroupName without a parent FormGroup directive.

    See the forked Stackblitz to see how the fixes changed the behavior.