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

问题描述 投票:0回答:1

我想在我的应用程序栏中有一个菜单,该菜单可以从子组件中获取菜单项。我正在使用“ 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”,它将其菜单项传递给父组件。注意menuData是一个对象,其中包含类型为string和回调function的对象数组。

  ngOnInit(): void {

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

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

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

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

javascript angular angular-material
1个回答
0
投票

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

这样的东西

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

class ChildComponenet {
  // ...
  constrcutor(private appService: AppService) {}

  ngOnInit() {
    // ...
    this.appService.menuItems$.new(['home', 'about']);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.