【发布时间】:2020-11-02 22:12:27
【问题描述】:
我正在尝试在 Angular 7 中创建上下文菜单,但由于某种原因,我在控制台中收到“无法读取菜单属性”的错误...
我要做的是在我的数据表中右键单击一个单元格后有一个菜单
这是我的代码:
view.component.html
<td mat-cell *matCellDef="let action" (contextmenu)="onContextMenu($event, column)">
{{ action[column.columnId] }}</td>
<div style="visibility: hidden; position: fixed" [style.left]="contextMenuPosition.x"
[style.top]="contextMenuPosition.y" [matMenuTriggerFor]="contextMenu">
</div>
<mat-menu #contextMenu="matMenu">
<ng-template matMenuContent>
<button mat-menu-item (click)="onContextMenuAction1()">Action 1</button>
<button mat-menu-item (click)="onContextMenuAction2()">Action 2</button>
</ng-template>
</mat-menu>
view.component.ts
@Component({
templateUrl: 'view.component.html'
})
export class ViewComponent implements OnInit, OnDestroy, AfterViewInit {
@ViewChild(MatSort) sort: MatSort;
@ViewChild(MatPaginator) paginator: MatPaginator;
contextMenu: MatMenuTrigger;
contextMenuPosition = { x: '0px', y: '0px' };
selection = new SelectionModel<TableRow>(true, []);
primaryTableValue: any;
constructor(private actionService: ActionService, private route: ActivatedRoute, private router: Router, public dialog: MatDialog, ) {
// Init these two fields on a dummy ViewData so that the mat-table does not throw errors.
this.viewData = {
ColumnObjects: new Array(),
ViewData: {
DataRows: new Array()
}
};
}
ngOnInit() {
// Init the dataSource
this.dataSource = new ViewDataSource(this.actionService);
// Init the component the first time it is navigated to.
this.initData();
}
//Context Menu
onContextMenu(event: MouseEvent) {
event.preventDefault();
this.contextMenuPosition.x = event.clientX + 'px';
this.contextMenuPosition.y = event.clientY + 'px';
this.contextMenu.menu.focusFirstItem('mouse');
this.contextMenu.openMenu(); }
onContextMenuAction1() {
console.log('clicked1');
}
onContextMenuAction2() {
console.log('clicked2');
}
}
【问题讨论】:
标签: javascript angular angular-material angular7 contextmenu