我开始使用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或我必须手动这样做?
当前回答
一种常见的模式是创建带有路由、惰性加载模块和组件的特性。
路线: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
其他回答
使用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将一个新组件添加到指定的文件夹中
博士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。模块&你应该很好。
对于Angular v4及以上版本,只需使用:
ng g c componentName -m ModuleName
根据Angular文档,为特定模块创建组件的方法是:
ng g component <directory name>/<component name>
"目录名" = CLI生成特性模块的目录
例子:-
ng generate component customer-dashboard/CustomerDashboard
这将在customer-dashboard文件夹中为新组件生成一个文件夹,并使用CustomerDashboardComponent更新特性模块
阅读描述——route https://angular.io/cli/generate#module-command,
为了存档,您必须将该组件模块的路由添加到某个位置,并指定路由名称。
ng generate module component-name --module=any-parent-module --route=route-path