Create component & add it to a specific module with Angular-CLI Create component & add it to a specific module with Angular-CLI angular angular

Create component & add it to a specific module with Angular-CLI


To create a component as part of a module you should

  1. ng g module newModule to generate a module,
  2. cd newModule to change directory into the newModule folder
  3. ng g component newComponent to create a component as a child of the module.

UPDATE: Angular 9

Now it doesn't matter what folder you are in when generating the component.

  1. ng g module NewMoudle to generate a module.
  2. ng g component new-module/new-component to create NewComponent.

Note: When the Angular CLI sees new-module/new-component, it understands and translates the case to match new-module -> NewModule and new-component -> NewComponent. It can get confusing in the beginning, so easy way is to match the names in #2 with the folder names for the module and component.


ng g component nameComponent --module=app.module.ts


Not sure if maybe Alexander Ciesielski's answer was correct at the time of writing, but I can verify that this no longer works. It doesn't matter which directory in the project you run the Angular CLI. If you type

ng g component newComponent

it will generate a component and import it into the app.module.ts file

The only way you can use CLI to automatically import it into another module is by specifying

ng g component moduleName/newComponent

where moduleName is a module you've already defined in your project. If the moduleName doesn't exist, it'll put the component in moduleName/newComponent directory but still import it into app.module