不同组件中的 mat-menu 和按钮 [英] mat-menu and button in different components

查看:43
本文介绍了不同组件中的 mat-menu 和按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

<mat-menu #saveMenu="matMenu">...</mat-menu>

在 app-save-document 组件和

in app-save-document component and

<app-save-document></app-save-document>
<button mat-icon-button [matMenuTriggerFor]="saveMenu">

在另一个组件中.

如果我在不同的组件中有带有 [matMenuTriggerFor] 的 mat-menu 和按钮,我可以做些什么让按钮看到菜单吗?

if I have mat-menu and button with [matMenuTriggerFor] in different components, can I do something to make the button see the menu?

现在我有 ERROR 错误:mat-menu-trigger:必须传入一个 mat-menu 实例.

推荐答案

好吧,如果你想做这样的事情:

Well, if you want to do something like this:

<button mat-button [matMenuTriggerFor]="menu">Menu</button>
<other-component [matMenu]="menu"></other-component>
<mat-menu #menu="matMenu">
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>

你可以像这样编码:

import {Component,Input} from '@angular/core';
import {MatMenu} from '@angular/material';

@Component({
  selector: 'other-component',
  template: `
    This button is in another component:
    <button [matMenuTriggerFor]="matMenu">Click here to open menu</button>
  `,
})
export class OtherComponent {
  @Input() matMenu: MatMenu;
}

您可以在此stackblitz演示中看到上述示例.

You can see the above example working at this stackblitz demo.

另一种方法是(我认为这就是您想要的):您的触发按钮在父级内(但在子级外)而菜单本身是在子组件内定义的.

Another approach is (I think this is what you want): your trigger button is inside the parent (but outside the child) and the menu itself is defined inside the child component.

父组件:

<button mat-button [matMenuTriggerFor]="childComponentMenu?.menu">
    Menu in other component
</button>
<child-component></child-component>

export class ParentComponent {
  @ViewChild(ChildComponent) childComponentMenu: ChildComponent;
}

子组件:

@Component({
  selector: 'child-component',
  template: `
    <mat-menu>
      <button mat-menu-item>Item 1 (inside other component)</button>
      <button mat-menu-item>Item 2 (inside other component)</button>
    </mat-menu>
  `,
})
export class ChildComponent {
  @ViewChild(MatMenu, {static: true}) menu: MatMenu;
}


另一种方法

另一种方法,类似于上面的方法,但使用模板引用变量(注意子组件装饰器中的exportAs):

父组件:

<button mat-button [matMenuTriggerFor]="x.menu">
    Menu in other component
</button>
<child-component #x="menuInOtherComponent"></child-component>

export class ParentComponent {
}

子组件:

@Component({
  selector: 'child-component',
  template: `
    <mat-menu>
      <button mat-menu-item>Item 1 (inside other component)</button>
      <button mat-menu-item>Item 2 (inside other component)</button>
    </mat-menu>
  `,
  exportAs: 'menuInOtherComponent',
})
export class ChildComponent {
  @ViewChild(MatMenu, {static: true}) menu: MatMenu;
}

Stackblitz 演示

这篇关于不同组件中的 mat-menu 和按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆