【问题标题】:Cannot read property 'open' of undefined - menu in typescript无法读取未定义的属性“打开” - 打字稿中的菜单
【发布时间】:2020-05-28 21:42:05
【问题描述】:

我的菜单中的操作有问题。 我为这个项目使用了材质菜单和图标。 外墙菜单代码如下所示:

<mat-menu #rootMenu="matMenu" [overlapTrigger]="false">
  <ng-template matMenuContent let-element="element">
    <div *ngFor='let item of contextMenu' (click)="item.action(element)">
      <button *ngIf='!item.seperator' mat-menu-item [disabled]="item.disabled">
        <mat-icon>
          {{item.icon}}
        </mat-icon>
        <span>
          {{item.name}}
        </span>
      </button>
      <mat-divider *ngIf='item.seperator'></mat-divider>
    </div>
  </ng-template>
</mat-menu>

现在我向您展示我的菜单元素模型:

export class MenuElement {
  id?: string
  name?: string
  tooltip?: string
  icon?: string
  action: (element : any) => void
  disabled?: boolean = true
  seperator?: boolean = false
}

最后,组件 ts 中的部分菜单:

 constructor(public dialog: MatDialog) {      //#1
 ...
 this.contextMenu = 
 ...
 {
        name: 'Rename',
        icon: 'edit',
        action: this.openRenameDialog,
        disabled: true
 },
 ...

以及openRenameDialog函数:

  openRenameDialog(element: FileElement) {
    let dialogRef = this.dialog.open(RenameDialogComponent);
    dialogRef.afterClosed().subscribe(res => {
      if (res) {
        element.name = res;
        this.elementRenamed.emit(element);
      }
    });
  }

最后,这是我的错误:

core.js:5828 错误类型错误:无法读取未定义的属性“打开” 在 Object.openRenameDialog [作为操作] (lib-common.js:4857) 在 FileExplorerComponent_ng_template_8_div_0_Template_div_click_0_listener (lib-common.js:4550) 在 executeListenerWithErrorHandling (core.js:21593) 在 wrapListenerIn_markDirtyAndPreventDefault (core.js:21635) 在 HTMLDivElement。 (平台-browser.js:934) 在 ZoneDelegate.invokeTask (zone-evergreen.js:400) 在 Object.onInvokeTask (core.js:40744) 在 ZoneDelegate.invokeTask (zone-evergreen.js:399) 在 Zone.runTask (zone-evergreen.js:168) 在 ZoneTask.invokeTask [作为调用] (zone-evergreen.js:481)

任何想法我需要做什么?

编辑 1

对话框被注入,看#1

【问题讨论】:

  • 您是否将 Dialog 注入到组件构造函数中?
  • 你可能需要在构造函数constructor(public dialog: MatDialog) {}中注入对话框@
  • 对话框被注入,我更新它。原因在别处
  • 还有其他想法吗?
  • 你能创建一个最小的 Stackblitz 示例吗?

标签: angular typescript angular-material contextmenu


【解决方案1】:

尝试将“openRenameDialog”方法的语法更改为

openRenameDialog = (element: FileElement) => {
    // etc 
}

这可能是因为当您分配action: this.openRenameDialog 时,与this 的绑定是针对方法的上下文而不是类的上下文(这是实际定义对话框的位置)。

在旧版本的 JS 中,您需要使用 bind 来引用正确的上下文。但是,随着 ES6 中包含“胖箭头”,这种绑定会自动为您完成。

【讨论】:

    猜你喜欢
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    • 2019-12-15
    相关资源
    最近更新 更多