angularangular-material

Why is mat-icon not a know element?


I keep getting error NG8001: 'mat-icon' is not a known element when I build my angular project. I tried downgrading angular material from 16 to 15 to 12, but still the error persists.

Here is my app.component.html

<div class="page-container">
  <header>
    <div>
      <button mat-button class="menu-button">
        <mat-icon>menu</mat-icon>
      </button>

      <a routerLink="/">
        <span class="app-title">Hamburger Menu Demo</span>
      </a>
    </div>
  </header>
</div>

Here is my app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'side-nav';
}

Here is my app.module.ts

import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BrowserModule } from '@angular/platform-browser';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { NgModule } from '@angular/core';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    AppComponent,
    BrowserAnimationsModule,
    BrowserModule,
    MatIconModule,
    NgModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Here are my current angular versions

@angular-devkit/build-angular   16.1.5
@angular-devkit/core            16.1.5
@angular-devkit/schematics      16.1.5
@angular/cdk                    16.1.5
@angular/cli                    16.1.5
@angular/material               12.2.13
@schematics/angular             16.1.5

There are no other components in the project. What am I missing?


Solution

  • Difficult to diagnose without having access to the full project.

    That said...

    Your app.module.ts looks to be incorrect and should look like this.

    The NgModule in imports will cause a compilation error and throw the error you are getting.

    import { NgModule } from '@angular/core';
    import { MatIconModule } from '@angular/material/icon';
    import { BrowserModule } from '@angular/platform-browser';
    
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        BrowserAnimationsModule,
        MatIconModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    
    

    And as stated above why not use "@angular/material": "^16.1.5", ?