angular中内置模块有:
核心模块:@angular/core
通用模块:@angular/common
表单模块:@angular/forms
网络模块:@angular/http
……
angular中的自定义模块
前提:当我们项目比较小的时候可以不用自定义模块。但是当我们项目非常庞大的时候把所有的组件都挂载到根模块里面不是特别合适。所以这个时候我们就可以自定义模块来组织我们的项目。并且通过路由的懒加载来加载Angular自定义模块,也可以手动引入
一、手动引入创建的模块(不推荐)
创建文件
// 1、创建user模块 modules是自己命名的,user是创建的模块
ng g module modules/user
// 2、创建user里的组件 components是放组件的文件夹自己命名,home是组件
ng g component modules/user/components/home
ng g component modules/user/components/chrees
// 3、创建user的跟组件
ng g component modules/user
// 4、创建服务 第二个service是文件夹名,bigser是服务名
ng g service modules/user/service/bigser
上述命令执行后的结果如下:
引入
引入到app根模块中
1、先在user.module.ts
模块里暴露组件
2、在app.module.ts
里引入
import { UserModule } from './modules/user/user.module';
@NgModule({
……
imports: [
……
UserModule,
],
……
})
3、app.component.html
根模块使用
第一种使用方法,在app.component.html
里调用user及user的子组件
结果:
第二种方法,在app.component.html
里只调用user
在user.components.html
里调用user的子组件
两者结果一样
注意:不同之处在于user.module.ts
暴露的模块。使用第一种方式时,必须把user的子组件也暴露。使用第二种方式时,只需暴露user根模块就行,也就是UserComponent
二、懒加载引入创建的模块(推荐)
1、创建文件
// 1、创建content、produce模块 --routing是创建路由的意思
ng g module modules/content --routing
ng g module modules/product --routing
// 2、创建content、produce模块里的组件
ng g component modules/content/components/cone
ng g component modules/content/components/ctwo
ng g component modules/product/components/pone
ng g component modules/product/components/ptwo
// 3、创建content、produce模块的跟组件
ng g component modules/content
ng g component modules/product
上述命令执行后的结果如下:
2、引入
import { ProductModule } from './modules/product/product.module';
import { ContentModule } from './modules/content/content.module';
@NgModule({
……
imports: [
……
ProductModule,
ContentModule
],
……
})
3、配置路由
配置product、content的路由
这两个模块配置的路由不一样,具体原因看下面的细讲,此处先跳过
配置app的路由
使用:
结果
两个路由配置不一样的解释
1、同级别的配置模块及模块子组件
有跳过的作用,同级别嘛,显示子组件,父组件的内容就隐藏了,同时,注意地址栏输入
2、父子级别的配置模块及模块子组件
显示子组件的同时,父组件的内容不隐藏,注意地址栏显示