4
votes

I'm using p-panelmenu from the excellent prime-ng library.

<p-panelMenu [model]="items" (click)="onClicked(event)"></p-panelMenu>

Trouble is I can't work out how to get the menu to do anything. The examples on the primeNG website all display menus but don't trigger any actions on them.

How can I get the currently selected item? I note that there is a "command" callback on the menuItem class; but it seems crazy to define a callback for every menu item. Rather than just one callback that gets passed the selected menu item. What am I missing here?

2

2 Answers

2
votes

I had to write a recursive function to loop through the menu-items and sub-items and assign a command callback to each one:

export class TreeViewComponent implements OnInit {
  @Output() onSelectedChanged: EventEmitter<MenuItem> = new EventEmitter<MenuItem>();

  items : any[] = [];

  constructor (private contentService: ContentService) {
  }

  ngOnInit() {
      this.getFolders();
  }

  getFolders() {
    this.contentService.getFolders().subscribe(this.setItems);
  }

  setItems = (x: any) => {
      this.assignCallback(x);
      this.items = x.items;
  }

  assignCallback(item:MenuItem){
    if(item.items != null && item.items.length > 0) {
      item.items.forEach(x => this.assignCallback(x))
    }
    item.command = this.commandCallback;
  }

  commandCallback(ev){
    console.log(ev.item);
  }
}

I will leave the question open; there's got to be a better way?

0
votes

https://www.primefaces.org/primeng/#/menumodel

You might want to read the documentation on MenuItem type for most of PrimeNG's Menu components. Inside the list of options an item might have, there's a 'command' option which executes a callback.