To create a component as part of a module you should
ng g module newModule
to generate a module, cd newModule
to change directory into the newModule
folder 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.
ng g module NewMoudle
to generate a module.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
I didn't find an answer that showed how to use the cli to generate a component inside a top level module folder, and also have the component automatically added the the module's declaration collection.
To create the module run this:
ng g module foo
To create the component inside the foo module folder and have it added to the foo.module.ts's declaration collection run this:
ng g component foo/fooList --module=foo.module.ts
And the cli will scaffold out the module and component like this:
--EDIT the new version of the angular cli behaves differently. 1.5.5 doesn't want a module file name so the command with v1.5.5 should be
ng g component foo/fooList --module=foo
You can try below command, which describes the,
ng -> Angular
g -> Generate
c -> Component
-m -> Module
Then your command will be like:
ng g c user/userComponent -m user.module
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With