2016-11-17 27 views
37

我开始使用angular-cli,并且我已经阅读了很多以找到有关我想要做什么的答案...没有成功,所以我来到了这里。使用Angular-CLI为特定模块创建组件

有没有办法创建一个组件到一个新的模块?

例如为:ng g module newModule

ng g component newComponent,因为角CLI默认行为是把里面所有app.module新组件(如何将此组件添加到newModule ??)

。我想选择我的组件的位置,以便我可以创建分离的模块,并且不会在app.module内部拥有所有组件。使用angular-cli可以做到这一点,或者我必须手动执行此操作吗?

回答

47

要创建一个组件作为一个模块,你应该

  1. ng g module newModule生成一个模块的一部分,
  2. cd newModule改变目录到newModule文件夹
  3. ng g component newComponent创建一个组件作为一个孩子该模块。
+1

这正是要找的。谢谢@亚历山大。我认为他们应该把它放在Docs中。 –

+19

您也可以保留在项目根目录中,并使用模块名称“ng g component moduleName/componentName”作为前缀。 – JayChase

+0

在使用Angular CLI版本1.6.8时,我总是收到'指定的模块不存在'的错误sying,当我sepcify现有的模块时。它在我尝试以下命令时起作用:* ng生成service service1 --module = module1/module1.module.ts *。注意:我的服务名称是* service1 *,我的模块名称是* module1 * – Diallo

29

不知道Alexander Ciesielski的回答在写作时是否正确,但我可以验证这不再有效。运行Angular CLI的项目中的哪个目录无关紧要。如果您键入

ng g component newComponent 

它会生成一个组成部分,是通过指定

其导入到app.module.ts文件

您可以使用CLI将自动导入到另一个模块的唯一方法

ng g component moduleName/newComponent 

其中moduleName是您已经在项目中定义的模块。如果模块名不存在,它就会将组件置于MODULENAME/newComponent目录,但仍然将其导入到app.module

+2

这是我当时正确的答案..它正常工作。我创建了一个拉取请求,将这些信息添加到文档中。其中一个贡献者要求我删除cd-ing部分..最后将是1.'ng g module newModule' 2.根据他的'g g component new-module/newComponent'应该是new-module而不是newModule –

+0

只需指出,使用亚历山大Ciesielski技术和按预期工作。我应该注意到,我不需要创建仅仅需要创建文件夹的组件。所以我只是'mkdir'文件夹,然后在新创建的文件夹中运行n个组件newComponent。 –

+1

我想说,完整的答案是'ng g component moduleName/newComponent -m moduleName' – slavugan

14
​​
+0

这是完美的答案 – Imran

10

我没有找到答案,这展示了如何使用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 
0

添加组件的角4应用程序中使用角CLI

要将新的角4组件添加到应用程序,使用命令ng g component componentName。执行此命令后,Angular CLI在src\app下添加一个文件夹component-name。此外,相同的参考文件将自动添加到src\app\app.module.ts文件中。

组件应具有@Component装饰器功能,后面跟着class,它需要export ed。装饰函数@Component接受元数据。

采用了棱角分明CLI

要将新组件添加到特定的文件夹用命令添加到角4应用程序的特定文件夹的分量ng g component folderName/componentName

0

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

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

这是对我工作:

1 --> ng g module new-module 

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

如果不想它的目录使用--flat标志产生的组件。

0

使用这个简单的命令:

ng g c users/userlist 

users:您的模块名称。

userlist:您的组件名称。

相关问题