Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access MatDrawer using ViewChild is throwing error in Angular 8

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

like image 593
B.Balamanigandan Avatar asked Aug 31 '25 17:08

B.Balamanigandan


2 Answers

Change declaration from

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

to

@ViewChild('drawer', { static: true }) public drawer!: MatDrawer;
like image 122
Varun Ahuja Avatar answered Sep 02 '25 13:09

Varun Ahuja


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.

like image 24
ScottG Avatar answered Sep 02 '25 15:09

ScottG