What is an Angular Module?

    Another analogy to understand Angular modules is classes. In a class, we can define public or private methods. The public methods are the API that other parts of our code can use to interact with it while the private methods are implementation details that are hidden. In the same way, a module can export or hide components, directives, pipes and services. The exported elements are meant to be used by other modules, while the ones that are not exported (hidden) are just used inside the module itself and cannot be directly accessed by other modules of our application.

    To be able to define modules we have to use the decorator .

    In the example above, we have turned the class AppModule into an Angular module just by using the NgModule decorator. The NgModule decorator requires at least three properties: imports, declarations and bootstrap.

    The property imports expects an array of modules. Here's where we define the pieces of our puzzle (our application). The property expects an array of components, directives and pipes that are part of the module. The bootstrap property is where we define the root component of our module. Even though this property is also an array, 99% of the time we are going to define only one component.

    Here's how a basic module made up of just one component would look like:

    app/app.module.ts

    The file app.component.ts is just a "hello world" component, nothing interesting there. In the other hand, the file app.module.ts is following the structure that we've seen before for defining a module but in this case, we are defining the modules and components that we are going to be using.

    The first thing that we notice is that our module is importing the BrowserModule as an explicit dependency. The BrowserModule is a built-in module that exports basic directives, pipes and services. Unlike previous versions of Angular, we have to explicitly import those dependencies to be able to use directives like ngFor or ngIf in our templates.

    Given that the root (and only) component of our module is the AppComponent we have to list it in the array. Because in the declarations property we are supposed to define all the components or pipes that make up our application, we have to define the AppComponent again there too.

    Before moving on, there's an important clarification to make. There are two types of modules, root modules and feature modules.

    By convention, the root module should always be named AppModule.

    Bootstrapping an Application

    To bootstrap our module based application, we need to inform Angular which one is our root module to perform the compilation in the browser. This compilation in the browser is also known as "Just in Time" (JIT) compilation.

    main.ts

    In the next section we are going to see how to create a module with multiple components, services and pipes.