Angular-如何在父组件菜单的菜单项中传递回调

时间:2019-11-18 23:28:30

标签: javascript angular angular-material

我想在我的应用程序栏中有一个菜单,该菜单可以从子组件中获取菜单项。我正在使用Angular Material“ mat-menu”,并且能够显示菜单项,但似乎无法在子组件上启动关联的功能。

app.component.html(父级):

  <div>
    <mat-toolbar style="display: flex; flex-direction: row; justify-content: space-between; margin-bottom: 12px">
      <div>
        <button type="button" mat-icon-button id="btnMore" [matMenuTriggerFor]="appMenu" [matMenuTriggerData]="menuData">
          <mat-icon>more_horiz</mat-icon>
        </button>
        <mat-menu #appMenu="matMenu" xPosition="before">
            <ng-template matMenuContent let-aliasMenuItems="menuItems">
              <button mat-menu-item *ngFor="let item of aliasMenuItems" (click)="handleMenuAction(item.action)">
                {{item.text}}
              </button>
            </ng-template>
        </mat-menu>
      </div>
    </mat-toolbar>
  </div>
  <div>
    <router-outlet></router-outlet>
  </div>

这是app.component.ts(父级)。它从appService组件检索菜单数据。它还(应该)执行回调。

  ngOnInit() {
    this.appService.getMenuData().subscribe(menuData => this.menuData = menuData);
  }

  handleMenuAction(action: Function) {
      action();
  }

这是子组件“ company.component.ts”,它将其菜单项传递给app.service,以便可以由app.component检索。请注意, menuData 是一个对象,其中包含类型为 string 和回调 function 的对象数组。

  ngOnInit(): void {

    this._appService.setMenuData({
      menuItems: [
        {text: "Add Company", action: this.addCompany}
    ]});
  }

  addCompany(): void {
    this._router.navigate(['/company', 0])
  }

由于某些原因,点击事件处理程序未显示在我的Chrome开发者工具中。我希望单击菜单即可调用功能,而不仅仅是执行导航。

可能有更好的方法来解决此问题。如果是这样,请提供示例链接。 TIA。

编辑:Stackblitz位于https://stackblitz.com/edit/angular-nbzoe6

1 个答案:

答案 0 :(得分:0)

更新后的答案 根据您的stackblitz

当您决定调用菜单操作时,只需要将子组件的this绑定到新的菜单操作即可在子作用域中运行

类似这样的东西:

company-list.component.ts

  ngOnInit(): void {
    this._appService.setMenuData({
      menuItems: [
        {text: "Add Company", action: this.addCompany.bind(this)}
    ]});
  }

旧答案 您可以在{{1}中创建可观察的menuItems$并在appService中对其进行订阅,然后从子组件中向该可观察对象添加新的menuItem,app.component.ts中的menuItem将有新的价值

类似这样的东西

app.component

appService.ts

class AppService { // ... menuItems$: BehaviourSubject<any[]> = new BehaviourSubject([]); constrcutor() {} // ... }

app.component.ts

class AppComponenet { // ... menuItems: any[] = []; constrcutor(private appService: AppService) {} ngOnInit() { // ... this.appService.menuItems$.subscribe(newMenu => { this.menuItems = newMenu; }); } }

child.compnenet.ts