Search code examples
angularangular-materialcontextmenuangular-cdk

Angular CDK context menu - How do I catch the cdkContextmenuTriggerData from the cdkMenu template?


I need to pass data within the context menu dynamically. cdkContextmenuTriggerData does the work but I am confused about how to catch this data within cdkMenu.

Here is my code -

<ng-template #menu>
  <div cdkMenu>
    <button cdkMenuItem>Edit</button>
  </div>
</ng-template>

<div [cdkContextMenuTriggerFor]="menu" [cdkContextMenuTriggerData]="variable">Right click on me..</div>

Solution

  • The object that you pass to the cdkContextMenuTriggerData input is basically passed through to the [ngTemplateOutletContext]. More info about setting and accessing the context in the official docs here.

    So it can be accessed using the let- keyword in the scope of the template (more docs about structural directives and keyword itself here).

    Considering your variable looks something like this:

    let variable: { $implicit: { value: 'SomeValue' } }
    

    You should be able to access it like so:

    <ng-template #menu let-passedContext>
      <div cdkMenu>
        <button cdkMenuItem>Edit {{passedContext.value}}</button>
      </div>
    </ng-template>
    

    Here's a sample stackblitz.