2

I am new to Angular world. There is something which confuses me while learning it, why we need to import any module two times : once through Javascript 'import' statement and then putting it in 'import' array?

Why need to import the same thing two times? Same goes with other code parts : need to first import 'component' and then again need to put the same in 'declarations' array of @NgModule.

Why need to do that? I am not getting it.

Bharata
  • 13,509
  • 6
  • 36
  • 50
user3760959
  • 457
  • 1
  • 6
  • 18
  • Possible duplicate of [What is difference between declarations, providers and import in NgModule](https://stackoverflow.com/questions/39062930/what-is-difference-between-declarations-providers-and-import-in-ngmodule) – Andy Ray Jan 15 '18 at 06:56

2 Answers2

2

I'm guessing you're talking about your module files ?

First, you have this line

import { MyComponent } from './my-component.component';

this line allows the typescript compiler to say

Okay, I need the resources from that file, in this file.

In this case, you're importing a class.

The next line is

declarations: [MyComponent]

(Or imports or modules or providers etc.)

In this case, this is related to Angular : as you can see, you put those "imports" into the decorator of your module, @NgModule. This is internal Angular stuff, but it allows him to do the correct things with your classes. For instance, when you put injectable classes into the providers, it tells Angular to create single instances of thoses classes.

  • Is it kind of lazyload? Will the component file loaded into the browser when module is loading? – Jeeva J May 21 '19 at 12:49
  • No it's not. Lazy loaded modules are standalone modules that are loaded on route change (or according to your loading strategy). –  May 21 '19 at 12:58
  • Sorry I didn't mean Lazy load modules. I meant about the component files. Will the component and service files load into the browser when import fines? – Jeeva J May 21 '19 at 13:12
  • I don't understand your question. The import doesn't depend on the decorator, but on the final bundle. Importing files at TS level only make them available for the compiler, to create a bundle. –  May 21 '19 at 13:19
  • I understood. Thank you. The following link helped me. Files are loaded dynamically/lazily. https://medium.com/lacolaco-blog/angular-dynamic-importing-large-libraries-8ec079603d0 – Jeeva J May 21 '19 at 13:49
0

The keyword "import" is actually tells to import a module into the current module(module has class in it). But after @NgModule whatever we are importing using imports keyword those are only single instances of the modules/classes imported previously.

Please correct me if I am wrong.