【问题标题】:Trigger mat-menu in child component from parent component从父组件触发子组件中的 mat-menu
【发布时间】:2018-07-02 07:39:26
【问题描述】:

我使用 angular 6 和 angular-material。 右键单击打开 matMenu 以将其用作上下文菜单。 我当前的代码如下所示。

<span #contextMenuTrigger [matMenuTriggerFor]="contextMenu"></span>
<button (contextmenu)="openContextMenu($event)" mat-button >Open Context Menu</button>
<mat-menu #contextMenu="matMenu">
    <ng-container *ngFor="let item of config.items">
      <button mat-menu-item [matMenuTriggerFor]="submenu" (click)="actionSelected(item.label)">{{ item.label }}</button>
      <mat-menu #submenu="matMenu">
         <button *ngFor="let subItem of item.submenu" mat-menu-item (click)="actionSelected(subItem.label)">{{ subItem.label }}</button>
      </mat-menu>
    </ng-container>
  </mat-menu>

我正在像这样在我的打字稿组件类中以编程方式打开菜单。

@ViewChild('contextMenuTrigger', {read: MatMenuTrigger}) contextMenuTrigger:MatMenuTrigger;

  ngOnInit() {

  }

  openContextMenu(e) {
    e.preventDefault();
    this.contextMenuTrigger.openMenu();
  }

一切正常。

现在,对于真正的场景,我想要的是,我希望从父组件打开这个上下文菜单。 所以我把这部分移到了 app.component.html

<span #contextMenuTrigger [matMenuTriggerFor]="contextMenu"></span>
    <button (contextmenu)="openContextMenu($event)" mat-button >Open Context Menu</button>

我使用 EventEmitter 将 MatMenu 的实例(即 contextMenu)传递给父级。

但我的问题是如何在父组件中分配 matMenuTriggerFor 属性。 如果我将其从跨度中删除,则给出错误。

AppComponent.html:1 ERROR Error: mat-menu-trigger: must pass in an mat-menu instance.

当我做document.getElementById("span id").matMenuTriggerFor = my menu instance时也不工作。

请提出任何建议。如果需要任何进一步的信息,请告诉我。

【问题讨论】:

标签: angular typescript angular-material


【解决方案1】:

只是为了确保我正确阅读了您的问题,我假设您的方法 openContextMenu() 在子组件中?如果是这样,您可以在父组件中使用 ViewChild 以便从父组件访问该方法。所以是这样的:

父代码:

import { Component, ViewChild } from '@angular/core';

import { ChildComponent } from '/path/to/child.component';

@Component({})
export class ParentComponent {

  @ViewChild(ChildComponent) childComponent: ChildComponent;

  onClick(event) {
    childComponent.openContextMenu(event);
  }

}

【讨论】:

  • 父组件中没有。虽然我解决了。我想要的是 [matMenuTriggerFor]="contextMenu" 替换为 [matMenuTriggerFor]="childComponent?.contextMenu" 其中 childComponent 是 @ViewChild(ChildComponent) childComponent: ChildComponent; 在 parentComponent 正如你所说,contextMenu 是 @ViewChild('contextMenu',{read:MatMenu}) contextMenu: MatMenu 在 childComponent
  • 干得好——很高兴你把它修好了。很高兴我能为您提供至少一半的解决方案! :)
猜你喜欢
  • 1970-01-01
  • 2020-04-16
  • 2019-10-20
  • 1970-01-01
  • 2018-10-27
  • 2017-03-03
  • 2018-03-09
  • 2021-06-11
  • 1970-01-01
相关资源
最近更新 更多