在Angular 8中获取组件外部的参考变量

时间:2019-06-10 00:38:47

标签: angular typescript scope angular8

我有此代码是为了切换抽屉/侧边栏。

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-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。我该怎么做呢?我不断看到使用类似这样的示例:

@ViewChild('leftbar') sidebar: ElementRef;

我一直在研究这个问题,并且当模板位于ts组件文件中时,我从Angular 2得到了旧的答案。同样,通常,其中包含抽屉(或其他功能)的组件位于标头内部,而不是相反。为此是否完全有必要创建服务?如果是这样,怎么办?在Angular 8中,最简单,正确且最少的打字稿方式是什么?

1 个答案:

答案 0 :(得分:1)

最简单的方法是从标头组件中发出Output事件:

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