在 Angular 8 中获取组件外部的引用变量

Get reference variable outside of component in Angular 8

我有这个代码来切换抽屉/边栏。

app-component.html

<app-header></app-header>
<mat-toolbar color="accent">
  <mat-toolbar-row>
    <button mat-button (click)="leftbar.toggle()" fxHide="false" fxHide.gt-sm>
      <mat-icon>menu</mat-icon>
    </button>
    <span>Custom Toolbar</span>
  </mat-toolbar-row>
</mat-toolbar>
<mat-sidenav-container class="ng-container centered">
  <mat-sidenav #leftbar opened mode="side">
    <app-leftnav></app-leftnav>
  </mat-sidenav>
  <mat-sidenav-content>
    <router-outlet></router-outlet>
  </mat-sidenav-content>
</mat-sidenav-container>
<app-footer></app-footer>

如果我点击菜单图标,左侧栏会打开/关闭。没有打字稿或额外服务。它开箱即用。但是,我需要将 mat-toolbar 放在实际的 app-header 组件中。所以我改为这样做:

app-component.html

<app-header></app-header>
<mat-sidenav-container class="ng-container centered">
  <mat-sidenav #leftbar opened mode="side">
    <app-leftnav></app-leftnav>
  </mat-sidenav>
  <mat-sidenav-content>
    <router-outlet></router-outlet>
  </mat-sidenav-content>
</mat-sidenav-container>
<app-footer></app-footer>

header-component.html

<mat-toolbar color="accent">
  <mat-toolbar-row>
    <button mat-button (click)="leftbar.toggle()" fxHide="false" fxHide.gt-sm>
      <mat-icon>menu</mat-icon>
    </button>
    <span>Custom Toolbar</span>
  </mat-toolbar-row>
</mat-toolbar>

这不起作用,因为 #leftbar 并不像预期的那样为 header 组件所知。我该怎么做呢?我一直看到使用这样的示例:

@ViewChild('leftbar') sidebar: ElementRef;

我一直在研究这个问题,当模板在 ts 组件文件中时,我从 Angular 2 那里得到了旧答案。此外,通常,带有抽屉的组件(或任何功能)位于 header 内部,而不是相反。是否完全有必要为此创建服务?如果是这样,如何?在 Angular 8 中执行此操作的最简单、正确和最少的打字方法是什么?

最简单的方法是从您的 header 组件发出输出事件:

header.component.ts

export class HeaderComponent {
  @Output() menuButtonClicked = new EventEmitter();
  ...

header.component.html

<button mat-button (click)="menuButtonClicked.emit()"

app.component.html

<app-header (menuButtonClicked)="leftbar.toggle()"></app-header>
<mat-sidenav-container class="ng-container centered">
  <mat-sidenav #leftbar opened mode="side">
    Side bar
  </mat-sidenav>
  ...
</mat-sidenav-container>

Stackblitz Example