2

我无法从另一个组件打开 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;
}

错误图像

4

2 回答 2

3

除了您没有在布局组件中的 ViewChild 中将抽屉设置为静态之外,您的代码中的一切都是正确的。

@ViewChild('drawer', { static: true }) public drawer: MatDrawer;
于 2020-04-25T21:54:28.377 回答
0

在您的服务中,您应该@Injectable像这样更新您的装饰器:

@Injectable({
  providedIn: 'root'
})

您看到的错误基本上表明该服务在您的组件中未定义。换句话说,它没有被正确注入。上面的代码是在根 (AppModule) 提供服务的最简单方法,因此可以将其注入到您的组件中。

于 2020-04-21T17:03:47.980 回答