Контекстное меню «Невозможно прочитать свойство меню» Angular 7 - PullRequest
0 голосов
/ 13 июля 2020

Я пытаюсь создать контекстное меню в 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');
      }

}

1 Ответ

0 голосов
/ 14 июля 2020

Пожалуйста, объявите contextMenuTrigger как указано ниже.

впишите в ViewChild , как вы использовали в html из кнопка .

@ViewChild('contextMenuTrigger') contextMenu: MatMenuTrigger;
...