在教师管理中,我们将教师列表、新增、编辑三个组件放到了App模块中,虽说最后为其建立了单独的文件夹来实现了模块块,但这种模块化并不彻底。 # 模块初始化 本节中,我们参考App模块新Klass班级模块。首先建立`klass`文件夹并于该文件夹中建立`klass.module.ts`文件,然后将班级的相关组件全部都放到班级模块中,打造更加模块化的应用程序。 klass.module.ts ``` import {NgModule} from '@angular/core'; z /** * 班级模块 */ @NgModule({}) ➊ export class KlassModule { } ``` * ➊ 声明KlassModule类为angular的一个模块 # 组件初始化 与前面手动建立组件不同,我们在此使用前面安装的`angular-cli`来自动完成组件的创建。打开shell(或webstorm的Terminal)并进入`app/klass`文件夹,执行`ng g c index`命令, 回显信息如下: ``` panjiedeMac-Pro:klass panjie$ ng g c index CREATE src/app/klass/index/index.component.sass (0 bytes) ➊ CREATE src/app/klass/index/index.component.html (20 bytes) ➋ CREATE src/app/klass/index/index.component.spec.ts (621 bytes) ➌ CREATE src/app/klass/index/index.component.ts (266 bytes) ➍ UPDATE src/app/klass/klass.module.ts (200 bytes) ➎ ``` > `ng g c index`简写于:`ng generate component index`,也就是说我们刚刚运行`ng generate component index`命令也是可以的。直译为:调用`ng` 命令生成index组件。 * ➊ 创建组件的样式表文件 * ➋ 创建组件的V层文件 * ➌ 创建组件的单元测试文件 * ➍ 创建组件的C层,并与➊➋所创建的文件进行关联 * ➎ 将创建的组件自动添加到klass模块 所以此时klass.module.ts文件的样子已经自动变更为: ``` import {NgModule} from '@angular/core'; import { IndexComponent } from './index/index.component'; ① /** * 班级模块 */ @NgModule({ declarations: [IndexComponent] ② }) export class KlassModule { } ``` 自动生成的4个文件,其中的V层的`index.component.html`中自动填充了`<p>index works</p>`标签,C层的`index.component.ts`中自动进行了代码的初始化并实现了OnInit接口,`index.component.sass`是样式表文件,是以前我们以前使用的`css`的升级版,用法与`css`差不太多,`index.component.spec.ts`是个伟大的单元测试文件。 # 参考文档 | 名称 | 链接 | 预计学习时长(分) | | --- | --- | --- | | 源码地址 | [https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step3.2.1](https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step3.2.1) | - |