2
votes

I'm trying practice use Ngmodule and imports, so I moved this line: (from heroes.component.ts file) import { Hero } from './hero';

to app.module.ts file:

    import { Hero } from './hero';
    @NgModule({
        imports: [
         BrowserModule,
         FormsModule,
         routing,
         Hero
        ],

but i get this error:

[0] app/heroes.component.ts(20,11): error TS2304: Cannot find name 'Hero'

It's possible to let in the components just the basic import: import { Component, OnInit } from '@angular/core'; and move all the rest imports to NgModule? or have I restrictions?

2

2 Answers

1
votes

Yes, there are restrictions to what should be included inside an NgModule. Esentially a module groups together a set of functionality, you can only add components, directives, services and other modules to an NgModule, your hero import should be inside a component, not a module.

import { Hero } from './hero';
//This import should stay inside app.component.ts

So your files would be

//app.component.ts
import { Component } from '@angular/core';

import { Hero } from './hero';

@component({
  selector: 'my-app',
  template: `<p>A template goes in here</p>`
})
export class AppComponent {
  public hero: Hero;
}

And:

//app.module.ts
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';

@NgModule({
  imports: [ BrowserModule ], //other modules you require
  declarations: [ AppComponent ], //declares components and directives
  bootstrap: [ AppComponent ] //your root component
})
export class AppModule { }
1
votes

The reason that propery 'imports' in NgModule is not for import components but to import another modules (files where another NgModules , grouped by another components ).

Components can be moved to Ngmodule in 'imports:' property: the import line: import { } from '..'; and 'directives' line

Service can be moved to NgModule in 'providers:' property but the difference it's that service must to keep in the component the: import { } from '..';