将NgModule导入独立组件时触发NG2012错误的技术求助
解决NG2012错误:独立组件导入NgModule失败
问题根源
你的代码中FooModule没有正确应用@NgModule装饰器——缺少了开头的@符号,导致Angular编译器无法识别它是合法的NgModule,只会把它当作普通类处理。而独立组件的imports数组仅接受独立组件、指令、管道或合法NgModule,因此触发NG2012错误。
修复步骤
1. 修正FooModule的装饰器
给NgModule添加@符号,使其成为有效的Angular模块:
import { NgModule } from '@angular/core'; import { FooComponent } from './foo.component'; @NgModule({ declarations: [FooComponent], exports: [FooComponent], }) export class FooModule {}
2. 验证独立组件导入
修正后,独立组件ExampleStandaloneComponent导入FooModule即可正常编译:
import { Component } from '@angular/core'; import { FooModule } from './foo.module'; @Component({ selector: 'app-root', standalone: true, imports: [FooModule], template: `<app-foo></app-foo>`, }) export class ExampleStandaloneComponent {}
可选优化:直接导入独立组件
如果FooComponent本身是独立组件(即@Component中配置了standalone: true),你可以跳过NgModule,直接在独立组件中导入FooComponent,这更符合Angular独立组件的设计理念:
import { Component } from '@angular/core'; import { FooComponent } from './foo.component'; @Component({ selector: 'app-root', standalone: true, imports: [FooComponent], template: `<app-foo></app-foo>`, }) export class ExampleStandaloneComponent {}
内容的提问来源于stack exchange,提问作者Matthieu Riegler
相关产品推荐
相关产品推荐

