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

是否有一种方法可以为新模块创建组件?

例如:ng g module newModule

如何将该组件添加到newModule中??

因为angular-cli的默认行为是把所有新组件放到app.module中。我想选择我的组件将在哪里,这样我就可以创建单独的模块,而不会有我所有的组件在app.module。这是可能的使用angular-cli或我必须手动这样做?


当前回答

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

ng g component newComponent

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

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

ng g component moduleName/newComponent

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

其他回答

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

生成一个模块, cd newModule将目录更改为newModule文件夹 创建一个组件作为该模块的子组件。

更新:Angular 9

现在,生成组件时在哪个文件夹中都不重要了。

ng module NewModule生成一个模块。 new-module/new-component创建NewComponent。

注意:当Angular CLI看到new-module/new-component时,它会理解并转换case以匹配new-module -> NewModule和new-component -> NewComponent。刚开始可能会让人困惑,所以简单的方法是将#2中的名称与模块和组件的文件夹名称匹配。

首先,你必须使用以下命令创建一个新模块:

ng g module newModule

然后,你必须使用以下命令进入该目录:

cd command  
cd newModule

现在你可以继续使用下面的命令:

ng g component newComponent

这个组件会在那个模块中创建。

使用Angular CLI将一个组件添加到Angular 4应用中

要向应用中添加一个新的Angular 4组件,请使用命令ng g component componentName。执行这个命令后,Angular CLI会在src\app下添加一个文件夹component-name。同样,同样的引用也被添加到src\app\app.module中。Ts文件自动。

组件应该有一个@Component装饰器函数,后面跟着一个需要导出的类。@Component装饰器函数接受元数据。

使用Angular CLI将一个组件添加到Angular 4应用的特定文件夹中

使用命令ng g component folderName/componentName将一个新组件添加到指定的文件夹中

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

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

今天我在搭建一个Angular 9应用程序时遇到了这个问题。我得到了“模块不存在错误”每当我添加.module。Ts或.module到模块名。cli只需要模块名,不需要扩展名。假设我有一个模块名:brands.module。ts,我使用的命令是

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

一旦确认文件结构正确,就删除——dry-run。