如何将 id 绑定到 PrimeNg 菜单命令

How to bind id to PrimeNg menu command

我有一个包含项目列表的 table。我想将 PrimeNg Menu 用于下拉菜单选项,以导航到具有所选项目 ID 的其他页面。我想做的是,当我点击菜单项时,我想绑定所选项目的 id。

我的HTML看起来像这样

<tr *ngFor="let item of items" class="animated fadeIn">
    <td>{{item.category}}</td>
    <td>{{item.name}}</td>
    <td>{{item.date}}</td>
    <td>
       <div>
           <p-menu #tableMenu [popup]="true" [model]="tableMenuItems" appendTo="body"></p-menu>
               <button type="button" pButton icon="pi pi-ellipsis-v"
                   class="ui-button-secondary ui-button-rounded ui-button-transparent"
                   (click)="tableMenu.toggle($event)">
               </button>
       </div>
    </td>
</tr>

和我的.ts

this.tableMenuItems = [
  {
    label: 'View Item', command: (event) => {
      // this.viewItemDetail() // here I wanted to bind item.id of the selected item and navigate to item detail page
    }
  },
  {
    label: 'Edit Item', command: (event) => {
      this.editItem() // here I wanted to bind item.id of the selected item and navigate to item edit page
    }
  },
];

您可以创建一个 属性 来保存当前项目并在调用切换方法之前在点击事件中设置所选项目

组件

 selectedItem:any = null;
 ...
 ngOnInit(){

 this.tableMenuItems = [
  {
    label: 'View Item', command: (event) => {
       console.log(this.selectedItem);
      // this.viewItemDetail() // here I wanted to bind item.id of the selected item and navigate to item detail page
    }
  },
  {
    label: 'Edit Item', command: (event) => {
      this.editItem() // here I wanted to bind item.id of the selected item and navigate to item edit page
    }
  },
];
}

模板

<tr *ngFor="let item of items" class="animated fadeIn">
    <td>{{item.category}}</td>
    <td>{{item.name}}</td>
    <td>{{item.date}}</td>
    <td>
       <div>
           <p-menu #tableMenu [popup]="true" [model]="tableMenuItems" appendTo="body"></p-menu>
               <button type="button" pButton icon="pi pi-ellipsis-v"
                   class="ui-button-secondary ui-button-rounded ui-button-transparent"
                   (click)="selectedItem = item;tableMenu.toggle($event)">
               </button>
       </div>
    </td>
</tr>