I am new to Angular and I am trying to write a simple modularized application. But I get the following error:
Uncaught Error: Unexpected directive 'SomeComponent' imported by the module 'SomeModule'. Please add a @NgModule annotation.
Basically, I do not want to import all the services and components in app.module.ts
, I wanted to modularize the code and I failed.
This is the app.module.ts
@NgModule({ declarations: [ AppComponent, HomeComponent ], imports: [ BrowserModule, RouterModule.forRoot(appRoutes), HttpClientModule, ReactiveFormsModule, SomeModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
This is nested module:
@NgModule({ imports: [ CommonModule, SomeComponent ], providers: [SomeService], declarations: [], exports: [SomeComponent] }) export class SomeModule { }
This is the nested component:
@Component({ selector: 'app-index', templateUrl: './some.component.html', styleUrls: ['./some.component.css'] }) export class SomeComponent implements OnInit { somes: Array<ISome>; constructor(private http: HttpClient, private service: SomeService) {} ngOnInit() { this.getSomes(); } getSomes() { this.service.getSomes().subscribe(res => { this.somes = res; }); } }
You're trying to "import" a component in SomeModule
.
imports: [ CommonModule, SomeComponent ],
You import modules and declare components, which is exactly what the error message tells you -- you tried importing a directive SomeComponent
.
Unexpected directive 'SomeComponent' imported by the module 'SomeModule'.
Move the SomeComponent
from imports
to declarations
.
imports: [ CommonModule, ], providers: [SomeService], declarations: [ SomeComponent, ],
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With