我有这个代码来切换抽屉/matsidebar。
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>
如果我单击菜单图标,左侧栏将打开/关闭。没有 typescript 或额外服务。它开箱即用。但是,我需要将 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 中执行此操作的最简单、正确且最少的 typescript 方法是什么?
最佳答案
最简单的方法是从 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>
关于angular - 在 Angular 8 中获取组件外部的引用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56519384/