4

I'm trying to set the behavior of MatSideNav through component file using a property of type MatDrawer in Angular version 8

TypeScript Code:

// Declaration
@ViewChild('drawer', { static: false }) public drawer: MatDrawer;

// Toggle the Side Nav bar
showSideNav(): void {
    this.drawer.toggle();
}

HTML Code:

<mat-drawer-container>
      <mat-drawer #drawer>
        <div>Side nav bar content</div>
      </mat-drawer>
      <div>Main content</div>
</mat-drawer-container>

Console Error:

ERROR TypeError: "this.drawer is undefined"

Kindly assist me how to access the MatDrawer element using @ViewChild

B.Balamanigandan
  • 4,713
  • 11
  • 68
  • 130

3 Answers3

5

Change declaration from

@ViewChild('drawer', { static: false }) public drawer: MatDrawer;

to

@ViewChild('drawer', { static: true }) public drawer!: MatDrawer;
pzaenger
  • 11,381
  • 3
  • 45
  • 46
Varun Ahuja
  • 51
  • 2
  • 3
1

In my case, the problem was because I had not imported MatSidenavModule in my Angular module. I could still refer to MatDrawer without error because I had Material installed, but it was not in the module import list.

ScottG
  • 534
  • 4
  • 9
0

I was able to resolve similar issue by passing the mat-drawer / sidenav id in the child component using @Input decorator, so in case of OP's problem statement something like this might work.

// Declaration
@Input drawerHandler: MatDrawer;

// Toggle the Side Nav bar
showSideNav(): void {
    this.drawerHandler.toggle();
}

And in template pass this input id value using a property binding

<mat-drawer-container>
      <mat-drawer #drawer [drawerHandler]="drawer">
        <div>Side nav bar content</div>
      </mat-drawer>
      <div>Main content</div>
</mat-drawer-container>
Ady
  • 584
  • 8
  • 16