[Fixed] how exactly should i import MatDrawer and MatDrawerContainer in app.module.ts? angular 9

Issue

I was trying to use angular material to open a side nav when I click on the toolbar icon. Everything works fine until I try to actually open the navbar, I got the error:

Unexpected directive ‘MatDrawer in @angular/material/sidenav/index.d.ts’ imported by the module ‘AppModule in /src/app/app.module.ts’. Please add a @NgModule annotation.

Here are the npm modules (package.json):

"@angular/animations": "^9.1.11",
"@angular/cdk": "^9.2.4",
"@angular/common": "~9.1.11",
"@angular/compiler": "~9.1.11",
"@angular/core": "~9.1.11",
"@angular/forms": "~9.1.11",
"@angular/material": "^9.2.4",
"@angular/platform-browser": "~9.1.11",
"@angular/platform-browser-dynamic": "~9.1.11",
"@angular/router": "~9.1.11",
"jQuery": "^1.7.4",
"jquery": "^3.5.1",
"rxjs": "~6.5.4",
"tslib": "^1.10.0",
"zone.js": "~0.10.2"

here is my app.module:

import { MatDrawer } from '@angular/material/sidenav';
import { MatDrawerContainer } from '@angular/material/sidenav';

@NgModule({
  declarations: [
    AppComponent,
    DressesComponent,
    LoadingSpinnerComponent,
    Toolbar,
    ButtonToggle,
    Sidenav
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    BrowserAnimationsModule,
    MatTableModule,
    MatSelectModule,
    MatDialogModule,
    MatInputModule,
    MatToolbarModule,
    MatIconModule,
    MatButtonToggleModule,
    MatDrawer,
    MatDrawerContainer
  
  ],
  providers: [DressesService, SidenavService],
  bootstrap: [AppComponent]
})
export class AppModule { }

and app.component.html:

<html dir="rtl" lang="he">
    <toolbar></toolbar>
    <side-nav></side-nav>
</html>

Solution

To import components and directives etc, you import their modules, not the actual components and directives. So you need to import MatSidenavModule instead of MatDrawer, MatDrawerContainer:

import {MatSidenavModule} from '@angular/material/sidenav';

@NgModule({
  declarations: [
    AppComponent,
    DressesComponent,
    LoadingSpinnerComponent,
    Toolbar,
    ButtonToggle,
    Sidenav
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    BrowserAnimationsModule,
    MatTableModule,
    MatSelectModule,
    MatDialogModule,
    MatInputModule,
    MatToolbarModule,
    MatIconModule,
    MatButtonToggleModule,
    MatSidenavModule //<-- this one
  
  ],
  providers: [DressesService, SidenavService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Leave a Reply

(*) Required, Your email will not be published