[angular] Create component to specific module with Angular-CLI

I'm starting to use angular-cli and I've already read a lot to find an answer about what I want to do...no success, so I came here.

Is there a way to create a component to a new module?

e.g.: ng g module newModule

ng g component newComponent (how to add this component to newModule??)

because the angular-cli default behavior is to put all new components inside app.module. I would like to choose where my component will be, so that I can create separated modules and won't have all my components inside app.module . It is possible to do that using angular-cli or do I have to do this manually?

This question is related to angular typescript angular-cli

The answer is


Add a component to the Angular 4 app using Angular CLI

To add a new Angular 4 component to the app, use command ng g component componentName. After execution of this command, Angular CLI adds a folder component-name under src\app. Also, the references of the same is added to src\app\app.module.ts file automatically.

A component shall have a @Component decorator function followed by a class which needs to be exported. The @Component decorator function accepts meta data.

Add a component to specific folder of the Angular 4 app using Angular CLI

To add a new component to a specific folder use the command ng g component folderName/componentName


  1. You can generate a Module using ng generate module <module name>.
  2. Then use this command to generate a component related to that module, ng generate component <component name> --module=<module name>

1.- Create your feature module as usual.

ng generate module dirlevel1/module-name

2.- You can specify the ROOT PATH of your project in --module ( only in --module, (/) root points to your PROJECT ROOT and IS NOT THE SYSTEM ROOT!!!)

ng generate component dirlevel1/component-name --module /src/app/dirlevel1/module-name.module.ts

Real Example:

ng generate module stripe/payment-methods-list
ng generate component stripe/payment-methods-list --module=/src/app/stripe/payment-methods-list/payment-methods-list.module.ts 

Output:

CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.scss (0 bytes)
CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.html (39 bytes)
CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.spec.ts (768 bytes)
CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.ts (322 bytes)
UPDATE src/app/stripe/payment-methods-list/payment-methods-list.module.ts (311 bytes)
[OK] Generated component!

Tested with Angular CLI: 9.1.4


I use this particular command for generating components inside a module.

ng g c <module-directory-name>/<component-name>

This command will generate component local to the module. or You can change directory first by typing.

cd <module-directory-name>

and then create component.

ng g c <component-name>

Note: code enclosed in <> represent user specific names.


First generate module:

ng g m moduleName --routing

This will create a moduleName folder then Navigate to module folder

cd moduleName

And after that generate component:

ng g c componentName --module=moduleName.module.ts --flat

Use --flat for not creating child folder inside module folder


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


  1. First, you generate a module by executing.
ng g m modules/media

this will generate a module called media inside modules folder.

  1. Second, you generate a component added to this module
ng g c modules/media/picPick --module=modules/media/media.module.ts

the first part of the command ng g c modules/media/picPick will generate a component folder called picPick inside modules/media folder witch contain our new media module.

the second part will make our new picPick component declared in media module by importing it in the module file and appending it to declarations array of this module.

working tree

enter image description here


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:

enter image description here

--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

Read the description of --route https://angular.io/cli/generate#module-command,

To archive such, you must add the route of that component-module to somewhere and specify the route name.

   ng generate module component-name --module=any-parent-module --route=route-path

A common pattern is to create a feature with a route, a lazy loaded module, and a component.

Route: myapp.com/feature

app-routing.module.ts

{ path: 'feature', loadChildren: () => import('./my-feature/my-feature.module').then(m => m.MyFeatureModule) },

File structure:

app   
+---my-feature
¦   ¦   my-feature-routing.module.ts
¦   ¦   my-feature.component.html
¦   ¦   my-feature.component.css
¦   ¦   my-feature.component.spec.ts
¦   ¦   my-feature.component.ts
¦   ¦   my-feature.module.ts

This can all be done in the cli with:

ng generate module my-feature --module app.module --route feature

Or shorter

ng g m my-feature --module app.module --route feature

Or if you leave out the name the cli will prompt you for it. Very useful when you need to create several features

ng g m --module app.module --route feature

For Angular v4 and Above, simply use:

ng g c componentName -m ModuleName

Go to module level/we can also be in the root level and type below commands

ng g component "path to your component"/NEW_COMPONENT_NAME -m "MODULE_NAME"

Example :

ng g component common/signup/payment-processing/OnlinePayment -m pre-login.module

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

According to Angular docs the way to create a component for specific module is,

ng g component <directory name>/<component name>

"directory name" = where the CLI generated the feature module

Example :-

ng generate component customer-dashboard/CustomerDashboard

This generates a folder for the new component within the customer-dashboard folder and updates the feature module with the CustomerDashboardComponent


If you have multiple apps declared in .angular-cli.json ( e.g. in case working on feature module)

"apps": [{
    "name": "app-name",
    "root": "lib",
    "appRoot": ""
}, {...} ]

You can :

ng g c my-comp -a app-name

-a stands for --app (name)


if you want to create along with your module try this

  ng generate m module_name --routing &&  ng generate c component_name

I am having the similar issues with multiple modules in application. A component can be created to any module so before creating a component we have to specify the name of the particular module.

'ng generate component newCompName --module= specify name of module'

First run ng g module newModule . Then run ng g component newModule/newModule --flat


ng g c componentName --module=path-to-your-module-from-src-folder

example:

ng g c testComponent --module=/src/app/home/test-component/test-component.module

I ran into this issue today while scaffolding an Angular 9 application. I got the "module does not exist error" whenever I added the .module.ts or .module to the module name. The cli only needs the name of the module with no extension. Assuming I had a module name: brands.module.ts, the command I used was

ng g c path/to/my/components/brands-component -m brands --dry-run

remove the --dry-run once you've confirmed the file structure is correct.


this is what worked for me :

1 -->  ng g module new-module

2 -->  ng g c new-module/component-test --module=new-module/new-module.module.ts

If you want to generate a component without its directory use --flat flag.


I created component based child module with specific Root Folder

That cli command below i specified,please check out

ng g c Repair/RepairHome -m Repair/repair.module

Repair is Root Folder of our child module

-m is --module

c for compount

g for generate


Use this simple command:

ng g c users/userlist

users: Your module name.

userlist: Your component name.



Make a module, service and component in particular module

Basic:

    ng g module chat     
    ng g service chat/chat -m chat
    ng g component chat/chat-dialog -m chat

    In chat.module.ts:
        exports: [ChatDialogComponent],
        providers: [ChatService]

    In app.module.ts:

        imports: [
            BrowserModule,
            ChatModule
        ]

    Now in app.component.html:
        <chat-dialog></chat-dialog>


LAZY LOADING:
    ng g module pages --module app.module --route pages

        CREATE src/app/pages/pages-routing.module.ts (340 bytes)
        CREATE src/app/pages/pages.module.ts (342 bytes)
        CREATE src/app/pages/pages.component.css (0 bytes)
        CREATE src/app/pages/pages.component.html (20 bytes)
        CREATE src/app/pages/pages.component.spec.ts (621 bytes)
        CREATE src/app/pages/pages.component.ts (271 bytes)
        UPDATE src/app/app-routing.module.ts (8611 bytes)       

    ng g module pages/forms --module pages/pages.module --route forms

        CREATE src/app/forms/forms-routing.module.ts (340 bytes)
        CREATE src/app/forms/forms.module.ts (342 bytes)
        CREATE src/app/forms/forms.component.css (0 bytes)
        CREATE src/app/forms/forms.component.html (20 bytes)
        CREATE src/app/forms/forms.component.spec.ts (621 bytes)
        CREATE src/app/forms/forms.component.ts (271 bytes)
        UPDATE src/app/pages/pages-routing.module.ts (437 bytes)

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to angular-cli

Why powershell does not run Angular commands? ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead Angular CLI Error: The serve command requires to be run in an Angular project, but a project definition could not be found Could not find module "@angular-devkit/build-angular" How to remove package using Angular CLI? How to set environment via `ng serve` in Angular 6 Error: Local workspace file ('angular.json') could not be found How do I deal with installing peer dependencies in Angular CLI? How to iterate using ngFor loop Map containing key as string and values as map iteration how to format date in Component of angular 5