问题描述
我的菜单中的操作有问题.我为此项目使用了材料菜单和图标.wain菜单代码如下所示:
I have issue with action in my menu.I using material menu and icons for this project.The wain menu code looks like this:
<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>
现在,我向您展示我的菜单元素模型:
Now i show you my menu element model:
export class MenuElement {
id?: string
name?: string
tooltip?: string
icon?: string
action: (element : any) => void
disabled?: boolean = true
seperator?: boolean = false
}
最后,组件ts中的菜单的一部分:
And at the end, part of menu in component ts:
constructor(public dialog: MatDialog) { //#1
...
this.contextMenu =
...
{
name: 'Rename',
icon: 'edit',
action: this.openRenameDialog,
disabled: true
},
...
和openRenameDialog函数:
And openRenameDialog function:
openRenameDialog(element: FileElement) {
let dialogRef = this.dialog.open(RenameDialogComponent);
dialogRef.afterClosed().subscribe(res => {
if (res) {
element.name = res;
this.elementRenamed.emit(element);
}
});
}
最后,这是我的错误:
有什么想法我需要做什么?
Any ideas what i need to do?
已插入对话框,外观为#1
Dialog was injected, look #1
推荐答案
尝试将"openRenameDialog"方法的语法更改为
Try changing the syntax of the "openRenameDialog" method to
openRenameDialog = (element: FileElement) => {
// etc
}
之所以会发生这种情况,是因为当您分配action: this.openRenameDialog
时,与this
的绑定的目标是方法的上下文,而不是类的上下文(实际上是在其中定义对话框的地方).
This is probably happening because when you assign action: this.openRenameDialog
, the binding to this
is targeting the context of the method instead of the context of the class (which is where dialog is actually defined).
在旧版JS中,您将需要使用bind
来引用正确的上下文.但是,在ES6中包含胖箭头"后,此绑定将自动为您完成.
In older versions of JS you would need to use bind
to reference the correct context. However, with the inclusion of "fat arrows" in ES6, this binding is automatically being done for you.
这篇关于无法读取未定义的属性"open"-打字稿中的菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!