首页 文章

使用Angular-CLI为特定模块创建组件

提问于
浏览
70

我开始使用angular-cli,我已经阅读了很多内容,以便找到关于我想做什么的答案......没有成功,所以我来到这里 .

有没有办法为新模块创建组件?

例如: ng g module newModule

ng g component newComponent (如何将此组件添加到newModule ??)

因为angular-cli默认行为是将所有新组件放在 app.module 中 . 我想选择我的组件的位置,以便我可以创建单独的模块,并且不会在 app.module 中包含所有组件 . 使用angular-cli可以做到这一点,还是我必须手动执行此操作?

12 回答

  • 2

    如果您在.angular-cli.json中声明了多个应用程序(例如,在处理功能模块时)

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

    您可以 :

    ng g c my-comp -a app-name
    

    -a代表--app(名字)

  • 95

    要创建组件作为模块的一部分,您应该

    • ng g module newModule 生成一个模块,

    • cd newModule 将目录更改为 newModule 文件夹

    • ng g component newComponent 将组件创建为模块的子组件 .

  • 47

    不确定Alexander Ciesielski在撰写本文时的答案是否正确,但我可以证实这不再适用 . 运行Angular CLI的项目中的哪个目录无关紧要 . 如果你输入

    ng g component newComponent
    

    它将生成一个组件并将其导入app.module.ts文件

    使用CLI自动将其导入另一个模块的唯一方法是指定

    ng g component moduleName/newComponent
    

    其中moduleName是您已在项目中定义的模块 . 如果moduleName不存在,它会将组件放在moduleName / newComponent目录中,但仍然将其导入app.module

  • 0
    ng g component nameComponent --module=app.module.ts
    
  • 52

    我没有找到一个答案,显示如何使用cli在顶级模块文件夹中生成组件,并且还让组件自动添加模块的声明集合 .

    要创建模块,请运行以下命令:

    ng g module foo
    

    要在foo模块文件夹中创建组件并将其添加到foo.module.ts的声明集合,请运行以下命令:

    ng g component foo/fooList --module=foo.module.ts
    

    并且cli将支持模块和组件,如下所示:

    enter image description here

    --EDIT新版本的角度cli表现不同 . 1.5.5不需要模块文件名,因此v1.5.5的命令应该是

    ng g component foo/fooList --module=foo
    
  • 1

    这对我有用:

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

    如果要生成没有其目录的组件,请使用 --flat flag .

  • 4

    你可以尝试下面的命令,它描述了,

    ng -> Angular 
    g  -> Generate
    c  -> Component
    -m -> Module
    

    然后你的命令就像:

    ng g c user/userComponent -m user.module
    
  • 18

    对于Angular v4及更高版本,只需使用:

    ng g c componentName -m ModuleName
    
  • 0

    使用这个简单的命令:

    ng g c users/userlist
    

    users :您的模块名称 .

    userlist :您的组件名称 .

  • 0

    根据Angular docs,为特定模块创建组件的方法是,

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

    “directory name”= CLI生成功能模块的位置

    示例: -

    ng generate component customer-dashboard/CustomerDashboard
    

    这将在customer-dashboard文件夹中为新组件生成一个文件夹,并使用CustomerDashboardComponent更新要素模块

  • 6

    Add a component to the Angular 4 app using Angular CLI

    要向应用程序添加新的Angular 4组件,请使用命令 ng g component componentName . 执行此命令后,Angular CLI在 src\app 下添加了一个文件夹 component-name . 此外,它的引用会自动添加到 src\app\app.module.ts 文件中 .

    组件应具有 @Component 装饰器函数,后跟 class ,需要 export . @Component 装饰器函数接受元数据 .

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

    要将新组件添加到特定文件夹,请使用命令 ng g component folderName/componentName

  • 1

    我在应用程序中遇到了多个模块的类似问题 . 可以为任何模块创建组件,因此在创建组件之前,我们必须指定特定模块的名称 .

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

相关问题