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

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

例如:ng g module newModule

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

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


当前回答

我使用这个特殊的命令在模块内生成组件。

ng g c <module-directory-name>/<component-name>

该命令将在模块本地生成组件。 或者您可以先输入更改目录。

cd <module-directory-name>

然后创建组件。

ng g c <component-name>

注意:<>中包含的代码表示用户特定的名称。

其他回答

一种常见的模式是创建带有路由、惰性加载模块和组件的特性。

路线: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

博士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。模块&你应该很好。

1.-像往常一样创建你的特性模块。

ng generate module dirlevel1/module-name

2.-你可以在——module中指定项目的根路径(只有在——module中,(/)根指向你的项目根,而不是系统根!!)

ng generate component dirlevel1/component-name --module /src/app/dirlevel1/module-name.module.ts

真实的例子:

ng generate module stripe/payment-methods-list
ng generate component stripe/payment-methods-list --module=/src/app/stripe/payment-methods-list/payment-methods-list.module.ts 

输出:

CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.scss (0 bytes)
CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.html (39 bytes)
CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.spec.ts (768 bytes)
CREATE src/app/stripe/payment-methods-list/payment-methods-list.component.ts (322 bytes)
UPDATE src/app/stripe/payment-methods-list/payment-methods-list.module.ts (311 bytes)
[OK] Generated component!

用Angular CLI测试:9.1.4

如果你在.angular-cli中声明了多个应用。Json(例如在处理特性模块的情况下)

"apps": [{
    "name": "app-name",
    "root": "lib",
    "appRoot": ""
}, {...} ]

你可以:

ng g c my-comp -a app-name

-a代表——app (name)

这应该可以工作:

共享/components/info-card——module=/src/app/shared/shared.module.ts

注:

Ng g c等价于Ng generate component Shared /components/info-card在我项目的src/app中 目录&这是我如何使用它来创建一个组件 在共享/components目录中输入InfoCardComponent (没有指定src/app)。 但是,要将这个新创建的组件添加到特定的模块,您需要 需要在模块的路径中包含/src/app,否则 它会说这个模块不存在。