好吧,如果你想做这样的事情:
<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>
你可以编码<other-component>
像这样:
import {Component,Input} from '@angular/core';
import {MatMenu} from '@angular/material/menu';
@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;
}
你可以看到上面的例子在这方面工作堆栈闪电战演示 https://stackblitz.com/edit/httpsstackoverflowcoma4834389864331661.
另一种方法
另一种方法是(我认为这就是你想要的):你的触发按钮 is 在父级内部 (but 在孩子之外)和menu本身已定义在孩子里面成分。
父组件:
<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 演示 https://stackblitz.com/edit/httpsstackoverflowcoma4834389864331662