Angular--自定义模块
发布日期:2021-05-06 01:25:50 浏览次数:26 分类:技术文章

本文共 1361 字,大约阅读时间需要 4 分钟。

1. Angular–自定义模块


当我们项目比较小的时候可以不用自定义模块。但是当我们项目非常庞大的时候把所有的组 件都挂载到根模块里面不是特别合适(影响效率)。所以这个时候我们就可以自定义模块来组织我们的项目。

当项目比较大的时候,建议把功能差不多的组件封装成一个模块


1.1 创建模块

ng g module modules/user # 创建模块 ng g component modules/user # 创建模块的根组件

1.2 在模块中创建组件或者服务

ng g component modules/user/components/addressng g service    module/user/services/common

1.3 暴露组件

写法和app.module.ts的写法一模一样 如需要将自定义中的组件提供给其他模块使用 需将该组件暴露出去

user.module.ts

import {
NgModule } from '@angular/core';import {
CommonModule } from '@angular/common';import {
CommonService } from './services/common.service';import {
ProfileComponent } from './components/profile/profile.component';import {
AddressComponent } from './components/address/address.component';import {
OrderComponent } from './components/order/order.component';import {
UserComponent } from './user.component';@NgModule({
/*user模块里面的组件*/ declarations: [ProfileComponent, AddressComponent, OrderComponent, UserComponent], exports:[UserComponent,AddressComponent], /*暴露组件 让其他模块里面可以使用暴露的组件*/ /*引入服务*/ providers:[CommonService], /*引入模块*/ imports: [ CommonModule ]})export class UserModule {
}

1.4 在其他模块中引入自定义模块

这里是在根模块中引入

app.module.ts

//引入自定义模块import {
UserModule } from './module/user/user.module';// 自定义模块 imports: [ UserModule, ],

1.5 在其他模块中使用自定义模块

这里是在根模块中使用

app.module.html

调用用户模块

1.6 运行结果:

在这里插入图片描述



上一篇:MySQL--运算符
下一篇:Angular--UI框架Antd组件库介绍&安装&使用

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年04月04日 10时17分48秒