Angular Material元素报错:'mat-card-title'不是已知元素
解决Angular Material组件“未知元素”错误
问题场景
仪表盘组件代码:
<mat-card fxFlex fxFill> <mat-card-title fxLayout="column" fxLayoutAlign="center center"> <span class="mat-title">My Dashboard</span> </mat-card-title> </mat-card>
遇到错误:
'mat-card-title' is not a known element:
- If 'mat-card-title' is an Angular component, then verify that it is part of this module.
- If 'mat-card-title' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
原因分析
你把MatCardModule导入到了应用路由模块,但Angular组件只能识别其所属NgModule中导入的依赖模块,路由模块并非组件的直接归属模块,所以组件无法找到Material组件的定义。
解决步骤
定位组件所属模块
找到仪表盘组件(比如DashboardComponent)对应的NgModule文件,可能是dashboard.module.ts;如果组件直接在根模块下,就是app.module.ts。导入MatCardModule到目标模块
在该模块的imports数组中添加MatCardModule,示例如下:import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MatCardModule } from '@angular/material/card'; // 导入MatCardModule import { DashboardComponent } from './dashboard.component'; // 导入你的仪表盘组件 @NgModule({ declarations: [DashboardComponent], // 确保组件已声明 imports: [ CommonModule, MatCardModule // 加入到imports数组 ] }) export class DashboardModule { }(可选)共享模块场景
如果多个模块都需要用到Material组件,建议创建一个SharedModule,在其中导入并导出Material模块,然后其他业务模块只需导入SharedModule即可:import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MatCardModule } from '@angular/material/card'; @NgModule({ imports: [CommonModule, MatCardModule], exports: [MatCardModule] // 导出供其他模块使用 }) export class SharedModule { }
注意事项
- 不需要在路由模块中导入Material组件模块,除非路由模块本身声明了需要用到这些组件的组件。
- 不要随意添加
CUSTOM_ELEMENTS_SCHEMA来屏蔽错误,这会掩盖真正的模块导入问题,只有当你确实在使用Web Component时才需要添加。
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

