按ER圖首先生成基礎的教師實體以備用:使用編輯器打開前臺,并在shell中來到src/app/norm/entity文件夾,使用`ng g class course`生成課程實體。
```javascript
panjiedeMac-Pro:entity panjie$ ng g class course
CREATE src/app/norm/entity/course.spec.ts (154 bytes)
CREATE src/app/norm/entity/course.ts (24 bytes)
```
參考ER圖完成字段及構造函數初始化工作:
```javascript
import {Teacher} from './Teacher';
/**
* 課程
*/
export class Course {
id: number;
name: string;
teacher: Teacher;
constructor(data?: { id?: number, name?: string, teacher?: Teacher }) {
if (data) {
if (data.id !== undefined) {
this.id = data.id;
}
if (data.name !== undefined) {
this.name = data.name;
}
if (this.teacher) {
this.teacher = data.teacher;
}
}
}
}
```
# 組件初始化
本組件為course模塊的第一個組件,在新建組件前進行模塊的初始化,然后在course模塊下完成本組件的初始化。
使用shell進行src/app文件夾,使用命令生成一個帶有路由模塊的Course模塊。
```
panjiedeMac-Pro:app panjie$ ng g m course --routing
CREATE src/app/course/course-routing.module.ts (250 bytes)
CREATE src/app/course/course.module.ts (280 bytes)
```
進入自動生成的course文件夾,進一步生成add組件:
```
panjiedeMac-Pro:app panjie$ cd course/
panjiedeMac-Pro:course panjie$ ng g c add
CREATE src/app/course/add/add.component.sass (0 bytes)
CREATE src/app/course/add/add.component.html (18 bytes)
CREATE src/app/course/add/add.component.spec.ts (607 bytes)
CREATE src/app/course/add/add.component.ts (258 bytes)
UPDATE src/app/course/course.module.ts (344 bytes)
```
## V層
src/app/course/add/add.component.html
```html
<div class="row justify-content-center">
<div class="col-4">
<h2>添加課程</h2>
<form (ngSubmit)="onSubmit()" [formGroup]="formGroup">
<div class="form-group">
<label for="name">名稱</label>
<input type="text" class="form-control" id="name"
placeholder="名稱" formControlName="name">
</div>
<div class="form-group">
<label>任課教師</label>
<app-teacher-select (selected)="course.teacher"></app-teacher-select>
</div>
<div class="form-group">
<label>綁定班級</label>
<div>
<label><input type="checkbox"> 班級1</label>
<label><input type="checkbox"> 班級2</label>
</div>
</div>
<div class="form-group">
<button>保存</button>
</div>
</form>
</div>
</div>
```
## C層
src/app/course/add/add.component.ts
```typescript
import { Component, OnInit } from '@angular/core';
import {FormGroup} from '@angular/forms';
import {Course} from '../../norm/entity/course';
@Component({
selector: 'app-add',
templateUrl: './add.component.html',
styleUrls: ['./add.component.sass']
})
export class AddComponent implements OnInit {
formGroup: FormGroup;
course: Course;
constructor() { }
ngOnInit() {
}
onSubmit() {
}
}
```
## 單元測試
引用ReactiveFormsModule。
src/app/course/add/add.component.spec.ts
```typescript
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AddComponent],
imports: [
ReactiveFormsModule
]
})
.compileComponents();
}));
```

解析模板中的app-teacher-select已經學習過了三種方法:
1. 在測試模塊中直接引入`AppTeacherSelect`組件。
2. 新建一個`selector`同為`app-teacher-select`的新組件做為AppTeacherSelect組件的替身,并在測試模塊中引入該替身組件。
3. 在`TestModule`新建`selector`同為`app-teacher-select`的`AppTeacherSelect`組件,做為原`StudentModule`中的`AppTeacherSelect`組件的替身。
從筆者的實際使用經驗來看,第3種方案雖然會面臨一定的組件`selector`沖突風險,但仍然不失為當前的"最佳實踐"。

打開shell并來到項目src/app/test/component文件夾,使用如下命令建立測試專用的同名`AppTeacherSelect`組件。
```
panjiedeMac-Pro:component panjie$ ng g c TeacherSelect
CREATE src/app/test/component/teacher-select/teacher-select.component.sass (0 bytes)
CREATE src/app/test/component/teacher-select/teacher-select.component.html (29 bytes)
CREATE src/app/test/component/teacher-select/teacher-select.component.spec.ts (678 bytes)
CREATE src/app/test/component/teacher-select/teacher-select.component.ts (301 bytes)
UPDATE src/app/test/test.module.ts (633 bytes)
```
并將此組件聲明到`TestModule`中的`exports`以將其作為輸出項向其它模塊輸出。
src/app/test/test.module.ts
```typescript
exports: [
LoginComponent,
TeacherSelectComponent ?
],
```
* ? 輸出(暴露)組件
測試結果:

提示說需要一個FormGroup實例(這說明在C層沒有對formGroup進行實例化),同時于報錯信息中給出了解決方案,沒有比這種報錯內容更貼心的了。
## FormGroupBuild
前面已經學經過使用`new FormGroup`的方法實例化`FormGroup`。
src/app/course/add/add.component.ts
```typescript
ngOnInit() {
this.formGroup = new FormGroup({
name: new FormControl('')
});
}
```
本節展示另一個更為簡單的`FormBuilder`來實例化`FormGroup`,當表單項較多時使用`FormBuilder`能夠降低一些創建表單的復雜度,在生產項目中是一種較常用的形式。
src/app/course/add/add.component.ts
```typescript
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.formGroup = new FormGroup({ ?
name: new FormControl('') ?
}); ?
this.formGroup = this.formBuilder.group({
name: ['']
});
}
```

# 名稱驗證
按需求,課程的名稱不能為空,最少為2個字符。
## C層
src/app/course/add/add.component.ts
```typescript
ngOnInit() {
this.formGroup = this.formBuilder.group({
name: ['', [Validators.required, Validators.minLength(2)]]
});
}
```
## V層初始化
src/app/course/add/add.component.html
```html
<input type="text" class="form-control" id="name"
placeholder="名稱" formControlName="name" required?>
<small id="nameRequired" *ngIf="formGroup.get('name').dirty && formGroup.get('name').errors && formGroup.get('name').errors.required" class="form-text text-danger">請輸入課程名</small> ?
<small id="nameMinLength" *ngIf="formGroup.get('name').errors && formGroup.get('name').errors.minlength" class="form-text text-danger">課程名稱不得少于2個字符</small> ?
</div>
<button type="submit" [disabled]="formGroup.invalid" ?>保存</button>
```
## 單元測試
參考單元測試代碼如下:
src/app/course/add/add.component.spec.ts
```typescript
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {AddComponent} from './add.component';
import {FormControl, FormGroup, ReactiveFormsModule} from '@angular/forms';
import {TestModule} from '../../test/test.module';
import {FormTest} from '../../testing/FormTest';
import {By} from '@angular/platform-browser';
describe('course -> AddComponent', () => {
let component: AddComponent;
let fixture: ComponentFixture<AddComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AddComponent],
imports: [
ReactiveFormsModule,
TestModule
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AddComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
fit('should create', () => {
expect(component).toBeTruthy();
});
fit('requried校驗', () => {
// 初次渲染頁面時,不顯示校驗信息
expect(fixture.debugElement.query(By.css('#nameRequired'))).toBeNull();
// 輸入了長度為1的名稱,顯示校驗信息
const formTest: FormTest<AddComponent> = new FormTest(fixture);
formTest.setInputValue('#name', '1');
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('#nameRequired'))).toBeNull();
// 刪除輸入,顯示required
formTest.setInputValue('#name', '');
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('#nameRequired'))).toBeDefined();
});
fit('minLength校驗', () => {
// 輸入長度小于2的,顯示
const formTest: FormTest<AddComponent> = new FormTest(fixture);
formTest.setInputValue('#name', '1');
expect(fixture.debugElement.query(By.css('#nameMixLength'))).toBeDefined();
});
fit('button校驗', () => {
// 初始化時,不能點擊
let button: HTMLButtonElement = fixture.debugElement.query(By.css('button[type="submit"]')).nativeElement;
expect(button.disabled).toBeTruthy();
// 輸入合格的內容后可點擊
component.formGroup.get('name').setValue('1234');
fixture.detectChanges();
button = fixture.debugElement.query(By.css('button[type="submit"]')).nativeElement;
expect(button.disabled).toBeFalsy();
});
});
```
## 保存按鈕點擊測試
由于本組件的表單啟用了字段合規性校驗功能,所以在進行保存按鈕測試時需要表單的值是有效的。
src/app/course/add/add.component.spec.ts
```typescript
fit('點擊保存按鈕', () => {
component.formGroup.get('name').setValue('1234');
fixture.detectChanges();
spyOn(component, 'onSubmit');
FormTest.clickButton(fixture, 'button[type="submit"]');
expect(component.onSubmit).toHaveBeenCalled();
});
```

# 參考文檔
| 名稱 | 鏈接 | 預計學習時長(分) |
| --- | --- | --- |
| 源碼地址 | [https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step6.1.1](https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step6.1.1) | - |
- 序言
- 第一章:Hello World
- 第一節:Angular準備工作
- 1 Node.js
- 2 npm
- 3 WebStorm
- 第二節:Hello Angular
- 第三節:Spring Boot準備工作
- 1 JDK
- 2 MAVEN
- 3 IDEA
- 第四節:Hello Spring Boot
- 1 Spring Initializr
- 2 Hello Spring Boot!
- 3 maven國內源配置
- 4 package與import
- 第五節:Hello Spring Boot + Angular
- 1 依賴注入【前】
- 2 HttpClient獲取數據【前】
- 3 數據綁定【前】
- 4 回調函數【選學】
- 第二章 教師管理
- 第一節 數據庫初始化
- 第二節 CRUD之R查數據
- 1 原型初始化【前】
- 2 連接數據庫【后】
- 3 使用JDBC讀取數據【后】
- 4 前后臺對接
- 5 ng-if【前】
- 6 日期管道【前】
- 第三節 CRUD之C增數據
- 1 新建組件并映射路由【前】
- 2 模板驅動表單【前】
- 3 httpClient post請求【前】
- 4 保存數據【后】
- 5 組件間調用【前】
- 第四節 CRUD之U改數據
- 1 路由參數【前】
- 2 請求映射【后】
- 3 前后臺對接【前】
- 4 更新數據【前】
- 5 更新某個教師【后】
- 6 路由器鏈接【前】
- 7 觀察者模式【前】
- 第五節 CRUD之D刪數據
- 1 綁定到用戶輸入事件【前】
- 2 刪除某個教師【后】
- 第六節 代碼重構
- 1 文件夾化【前】
- 2 優化交互體驗【前】
- 3 相對與絕對地址【前】
- 第三章 班級管理
- 第一節 JPA初始化數據表
- 第二節 班級列表
- 1 新建模塊【前】
- 2 初識單元測試【前】
- 3 初始化原型【前】
- 4 面向對象【前】
- 5 測試HTTP請求【前】
- 6 測試INPUT【前】
- 7 測試BUTTON【前】
- 8 @RequestParam【后】
- 9 Repository【后】
- 10 前后臺對接【前】
- 第三節 新增班級
- 1 初始化【前】
- 2 響應式表單【前】
- 3 測試POST請求【前】
- 4 JPA插入數據【后】
- 5 單元測試【后】
- 6 惰性加載【前】
- 7 對接【前】
- 第四節 編輯班級
- 1 FormGroup【前】
- 2 x、[x]、{{x}}與(x)【前】
- 3 模擬路由服務【前】
- 4 測試間諜spy【前】
- 5 使用JPA更新數據【后】
- 6 分層開發【后】
- 7 前后臺對接
- 8 深入imports【前】
- 9 深入exports【前】
- 第五節 選擇教師組件
- 1 初始化【前】
- 2 動態數據綁定【前】
- 3 初識泛型
- 4 @Output()【前】
- 5 @Input()【前】
- 6 再識單元測試【前】
- 7 其它問題
- 第六節 刪除班級
- 1 TDD【前】
- 2 TDD【后】
- 3 前后臺對接
- 第四章 學生管理
- 第一節 引入Bootstrap【前】
- 第二節 NAV導航組件【前】
- 1 初始化
- 2 Bootstrap格式化
- 3 RouterLinkActive
- 第三節 footer組件【前】
- 第四節 歡迎界面【前】
- 第五節 新增學生
- 1 初始化【前】
- 2 選擇班級組件【前】
- 3 復用選擇組件【前】
- 4 完善功能【前】
- 5 MVC【前】
- 6 非NULL校驗【后】
- 7 唯一性校驗【后】
- 8 @PrePersist【后】
- 9 CM層開發【后】
- 10 集成測試
- 第六節 學生列表
- 1 分頁【后】
- 2 HashMap與LinkedHashMap
- 3 初識綜合查詢【后】
- 4 綜合查詢進階【后】
- 5 小試綜合查詢【后】
- 6 初始化【前】
- 7 M層【前】
- 8 單元測試與分頁【前】
- 9 單選與多選【前】
- 10 集成測試
- 第七節 編輯學生
- 1 初始化【前】
- 2 嵌套組件測試【前】
- 3 功能開發【前】
- 4 JsonPath【后】
- 5 spyOn【后】
- 6 集成測試
- 7 @Input 異步傳值【前】
- 8 值傳遞與引入傳遞
- 9 @PreUpdate【后】
- 10 表單驗證【前】
- 第八節 刪除學生
- 1 CSS選擇器【前】
- 2 confirm【前】
- 3 功能開發與測試【后】
- 4 集成測試
- 5 定制提示框【前】
- 6 引入圖標庫【前】
- 第九節 集成測試
- 第五章 登錄與注銷
- 第一節:普通登錄
- 1 原型【前】
- 2 功能設計【前】
- 3 功能設計【后】
- 4 應用登錄組件【前】
- 5 注銷【前】
- 6 保留登錄狀態【前】
- 第二節:你是誰
- 1 過濾器【后】
- 2 令牌機制【后】
- 3 裝飾器模式【后】
- 4 攔截器【前】
- 5 RxJS操作符【前】
- 6 用戶登錄與注銷【后】
- 7 個人中心【前】
- 8 攔截器【后】
- 9 集成測試
- 10 單例模式
- 第六章 課程管理
- 第一節 新增課程
- 1 初始化【前】
- 2 嵌套組件測試【前】
- 3 async管道【前】
- 4 優雅的測試【前】
- 5 功能開發【前】
- 6 實體監聽器【后】
- 7 @ManyToMany【后】
- 8 集成測試【前】
- 9 異步驗證器【前】
- 10 詳解CORS【前】
- 第二節 課程列表
- 第三節 果斷
- 1 初始化【前】
- 2 分頁組件【前】
- 2 分頁組件【前】
- 3 綜合查詢【前】
- 4 綜合查詢【后】
- 4 綜合查詢【后】
- 第節 班級列表
- 第節 教師列表
- 第節 編輯課程
- TODO返回機制【前】
- 4 彈出框組件【前】
- 5 多路由出口【前】
- 第節 刪除課程
- 第七章 權限管理
- 第一節 AOP
- 總結
- 開發規范
- 備用