Angular 2父组件模板无法使用子组件,添加声明仍报错
解决Angular报错:Unexpected directive 'FavoriteComponent' imported by the module 'AppModule'
兄弟,我一眼就看穿问题所在了——你大概率是不小心把FavoriteComponent塞进AppModule的imports数组里了!这是Angular新手常踩的坑,咱们一步步来解决:
1. 修正AppModule的配置
Angular的模块配置里,组件、指令、管道必须放在declarations数组中,而imports数组是专门用来导入其他NgModule(比如BrowserModule、FormsModule这类)的。你肯定是把组件错放到imports里了,导致Angular误以为它是一个模块,才会报错让你加@NgModule注解。
把你的app.module.ts改成下面这样就对了:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; // 导入你的组件 import { FavoriteComponent } from './favorite.component'; import { CoursesComponent } from './courses.component'; import { AppComponent } from './app.component'; // 别忘了导入根组件 @NgModule({ declarations: [ AppComponent, FavoriteComponent, // 组件就放在这里! CoursesComponent ], imports: [ BrowserModule // imports里只放NgModule,别放组件! ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
2. 确认你的组件代码没问题
看你贴的favorite.component.ts代码,完全符合Angular组件的写法:有正确的@Component装饰器,也导出了组件类,这部分不用改。
为什么会报这个错?
简单说:
declarations:告诉Angular这个模块包含哪些组件、指令、管道imports:告诉Angular这个模块需要依赖哪些其他NgModule
如果把组件放到imports里,Angular会尝试把它当作NgModule处理,但组件本身没有@NgModule注解,所以就会抛出这个错误。
内容的提问来源于stack exchange,提问作者SamuraiJack
相关产品推荐
相关产品推荐

