我开始使用angular-cli,我已经阅读了很多关于我想做什么的答案…没有成功,所以我来到这里。
是否有一种方法可以为新模块创建组件?
例如:ng g module newModule
如何将该组件添加到newModule中??
因为angular-cli的默认行为是把所有新组件放到app.module中。我想选择我的组件将在哪里,这样我就可以创建单独的模块,而不会有我所有的组件在app.module。这是可能的使用angular-cli或我必须手动这样做?
我开始使用angular-cli,我已经阅读了很多关于我想做什么的答案…没有成功,所以我来到这里。
是否有一种方法可以为新模块创建组件?
例如:ng g module newModule
如何将该组件添加到newModule中??
因为angular-cli的默认行为是把所有新组件放到app.module中。我想选择我的组件将在哪里,这样我就可以创建单独的模块,而不会有我所有的组件在app.module。这是可能的使用angular-cli或我必须手动这样做?
当前回答
我不知道这是不是把你们带到这里来的原因,但我想创建一个包含模块、路由和组件文件的文件夹。我希望将组件声明给我创建的模块。
为此,我发现这个命令非常有用。
Ng路径/to/folder/component—路由路径/to/folder/component
这将创建一个包含6个文件的文件夹。
CREATE path/to/folder/component/component-routing.module.ts (253 bytes)
CREATE path/to/folder/component/component.module.ts (297 bytes)
CREATE path/to/folder/component/component.component.html (26 bytes)
CREATE path/to/folder/component/component.component.spec.ts (655 bytes)
CREATE path/to/folder/component/component.component.ts (295 bytes)
CREATE path/to/folder/component/component.component.scss (0 bytes)
UPDATE path/to/folder/component/component.module.ts (379 bytes)
如果你不想要路由,你可以删除。
其他回答
如果你已经创建了你的组件而没有指向一个模块,你可以通过将它添加到声明中来直接将它添加到你的应用模块中
@NgModule({
declarations: [
FileManagerDetailsComponent <---this is ur page component
博士TL; 试试这个。通过模块的文件名指定模块名(不包括.ts扩展名) Ng c components/path-to-a-folder/component-name——module=app.module
注:
Ng g c是Ng generate component的缩写 如果您希望将组件添加到不同的模块中,我们将其添加到文件中 然后使用——module=collection.module 而不是——module=app。模块&你应该很好。
要将组件创建为模块的一部分,您应该
生成一个模块, 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中的名称与模块和组件的文件夹名称匹配。
我在angular CLI版本8.3中使用过以下命令,它通过生成在特定模块中声明的特定组件来工作。
移动到我们需要生成组件的特定文件夹 cd <组件路径> 调用下面的generate命令 Ng c <component-name>——module=<module-name>
例子
`ng g c login --module= app`
不确定Alexander Ciesielski的答案在撰写本文时是否正确,但我可以证实这不再适用。不管你在项目的哪个目录下运行Angular CLI。如果你输入
ng g component newComponent
它将生成一个组件并将其导入到app.module.ts文件中
使用CLI自动将其导入到另一个模块的唯一方法是指定
ng g component moduleName/newComponent
其中moduleName是您已经在项目中定义的模块。如果moduleName不存在,它会把组件放在moduleName/newComponent目录下,但仍然会把它导入app.module