How works angular 2/4/5 module file? How to create component using CLI?

In last article we  discussed on structure of the angular application.
No in this article i discuss on “app.module” file. Why its most important file in your applications?

In “app.module.ts” file located in “src/app” folder. In top declare all components that we have use in our applications. we need to declare in this file otherwise it gives error “declare NgModule to use these as part of application” also we need declare Global  services.


For our created components first import it then add Class name in declaration array. For example i have created one component name “Login” then if i need to import like ” import {Login} from “./pages/login” ” then our class name added in declaration section

@NgModule({
declarations: [
AppComponent,
Login,  // ADD your class name here.
]

How to create login component it will discuss in later part of the article. Same way if you have a services like API connection with your database for displaying the data. So first that services import in module then add that class in

Providers array. For Example I have created service name “AuthLogin” then first need to import like ” import {AuthLogin} from “./services/authlogin” ” then class name add in “providers” array like providers: [AuthLogin]

If we use angular default component then we need to declare in “imports” array.


Now learn How to create component & services using Angular CLI.

In above video it display how to create first component using CLI. For that need to open first command prompt then browser your project using command prompt then run following command ” ng g component pages/login ” when it it create component in pages/login folder and component name login it creates default files and also added entry in your module file.

Same way if you want to create services then you need to run command ” ng g service services/authlogin ”

In above video it display how to create first service using CLI. It creates files of service but we need to declare where we have to use that service. If we want to declare globally  then it added in “app.module.ts”  file looks like below screenshot.

These simple steps you can create component ,services in your application. Next article I discuss on Routing for Angular 2/4/5.

Spread the love
  • 35
  •  
  •  
  •  
  •  
  •  
  •  
  •