我无法从另一个组件打开 sidenav 错误出现在此问题所附的图像中。事实上,我想在我的代码中使用这种风格的 sidenav:
https://stackblitz.com/angular/lronayrmlye?file=src%2Fapp%2Fsidenav-autosize-example.ts
但我希望能够从另一个组件打开 sidenav
包含按钮的组件:navigation.component
包含 sidenav 的组件: layouts.component
sidebar.service.ts
import { Injectable, EventEmitter } from '@angular/core';
import { MatSidenav, MatDrawer } from '@angular/material/sidenav';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class SidenavService {
public sideNavToggleSubject: BehaviorSubject<any> = new BehaviorSubject(null);
constructor() { }
private drawer: MatDrawer;
setDrawer(drawer: MatDrawer) {
this.drawer = drawer;
}
toggle(): void {
this.drawer.toggle();
}
}
navigation.component.html
<mat-toolbar-row>
<button type="button" class= "open-sidebar" mat-button (click)="toggled()">
Toggle sidenav
</button>
</mat-toolbar-row>
navigation.component.ts
import { Component, OnInit , ChangeDetectorRef} from '@angular/core';
import { MediaMatcher } from '@angular/cdk/layout';
import { SidenavService } from '../services/sidenav.service';
import { MatSidenav } from '@angular/material/sidenav';
@Component({
selector: 'app-navigation',
templateUrl: './navigation.component.html',
styleUrls: ['./navigation.component.scss']
})
export class NavigationComponent {
constructor(
private sidenavService: SidenavService) { }
toggled() {
this.sidenavService.toggle();
}
}
layouts.component.html
<div>
<div class="mat-typography">
<app-navigation></app-navigation>
<router-outlet></router-outlet>
</div>
<mat-drawer-container class="example-container colorred" autosize>
<mat-drawer #drawer class="example-sidenav" position="end" mode="side">
<p>Auto-resizing sidenav</p>
<p *ngIf="showFiller">Lorem, ipsum dolor sit amet consectetur.</p>
<button (click)="showFiller = !showFiller" mat-raised-button>
Toggle extra text
</button>
</mat-drawer>
</mat-drawer-container>
</div>
layouts.component.ts
import { Component, VERSION as ngv , ViewChild} from '@angular/core';
import {MatSidenavModule,MatDrawer} from '@angular/material/sidenav';
import {SidenavService} from 'src/app/layouts/services/sidenav.service';
@Component({
selector: 'app-layouts',
templateUrl: './layouts.component.html',
styleUrls: ['./layouts.component.scss']
})
export class LayoutsComponent {
constructor(private sidenavService: SidenavService) {
}
@ViewChild('drawer') public drawer: MatDrawer;
ngOnInit() {
this.sidenavService.setDrawer(this.drawer);
}
showFiller = false;
}