我开始使用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或我必须手动这样做?
当前回答
这对我来说很管用:
1 --> ng g module new-module
2 --> ng g c new-module/component-test --module=new-module/new-module.module.ts
如果你想生成一个没有目录的组件,使用——flat标志。
其他回答
ng g c模块
然后在共享模块中创建头组件
ng g c shared/header --module=shared
如果需要同时创建组件和模块,可以使用命令
ng g m components/my-control && ng g c $_
这将在同一个目录中创建一个模块和组件,默认情况下,组件将被添加到closed模块中
我在应用程序中有多个模块的类似问题。可以为任何模块创建组件,因此在创建组件之前,必须指定特定模块的名称。
'ng generate component newCompName --module= specify name of module'
一种常见的模式是创建带有路由、惰性加载模块和组件的特性。
路线:myapp.com/feature
app-routing.module.ts
{ path: 'feature', loadChildren: () => import('./my-feature/my-feature.module').then(m => m.MyFeatureModule) },
文件结构:
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
这一切都可以在cli中完成:
ng generate module my-feature --module app.module --route feature
或更短
ng g m my-feature --module app.module --route feature
或者如果你省略了名字,cli会提示你输入。在需要创建多个特性时非常有用
ng g m --module app.module --route feature
不确定Alexander Ciesielski的答案在撰写本文时是否正确,但我可以证实这不再适用。不管你在项目的哪个目录下运行Angular CLI。如果你输入
ng g component newComponent
它将生成一个组件并将其导入到app.module.ts文件中
使用CLI自动将其导入到另一个模块的唯一方法是指定
ng g component moduleName/newComponent
其中moduleName是您已经在项目中定义的模块。如果moduleName不存在,它会把组件放在moduleName/newComponent目录下,但仍然会把它导入app.module