參考前面章節實現班級列表組件及班級新增組件的方法,先使用終端進行app/klass路徑,然后執行`ng g c edit`命令來創建班級編輯組件。
```
panjiedeMac-Pro:klass panjie$ ng g c edit
CREATE src/app/klass/edit/edit.component.sass (0 bytes)
CREATE src/app/klass/edit/edit.component.html (19 bytes)
CREATE src/app/klass/edit/edit.component.spec.ts (614 bytes)
CREATE src/app/klass/edit/edit.component.ts (262 bytes)
UPDATE src/app/klass/klass.module.ts (760 bytes)
```
接著我們找到klass/add/add.component.spec.ts, 修正單元測試名稱以及將`it`方法暫時修改為`fit`方法,并在終端中執行`ng test`命令來啟動單元測試。
klass/add/add.component.spec.ts
```
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { EditComponent } from './edit.component';
describe('klass EditComponent', () => {
let component: EditComponent;
let fixture: ComponentFixture<EditComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ EditComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(EditComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
fit('should create', () => {
expect(component).toBeTruthy();
});
});
```

在上個小節中,我們直接定義了兩個FormControl并直接綁定到了V層中。但V層中的表單中的字段較多時,就使用C層中有大量的表單變量,這與面象對象中的“封裝性”不相符。在angular中,我們可以將FormControl封裝到FormGroup中,然后將FormGroup綁定到form。這樣一來,CV層便建立起了如下關系:

## C層初始化
FormGroup的使用也非常的簡單:
klass/edit/edit.component.ts
```
import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup} from '@angular/forms';
@Component({
selector: 'app-edit',
templateUrl: './edit.component.html',
styleUrls: ['./edit.component.sass']
})
export class EditComponent implements OnInit {
formGroup: FormGroup; ?
constructor() {
}
ngOnInit() {
this.formGroup = new FormGroup({ ?
name: new FormControl(), ?
teacherId: new FormControl() ?
});
}
}
```
* ? 聲明變量
* ? 初始化,構造函數中接收的類型為`{}`
* ? 該對象中有兩個屬性,分別為name和teacherId,分別使用FormControl進行初始化,在初始化的過程中可以對該項賦值。
## V層初始化
klass/edit/edit.component.spec.ts
```
<h3>編輯班級</h3>
<form (ngSubmit)="onSubmit()" [formGroup]="formGroup"? >
<label for="name">名稱:<input id="name" type="text" formControlName="name"?/></label>
<label for="teacherId">教師ID:<input type="number" id="teacherId" formControlName="teacherId"?></label>
<button>更新</button>
</form>
```
* ? 使用`[formGroup]`將表單綁定到C層的`formGroup`變量
* ? 使用`formControlName`來指定該input對應的formGroup中的屬性
### 測試
FormGroup同樣屬于ReactiveFormsModule,則測試文件如下:
klass/edit/edit.component.spec.ts
```js
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [EditComponent],
imports: [
ReactiveFormsModule ①
]
})
.compileComponents();
}));
```

## 設置FormGroup中的值
除在初始化的過程中過FormGroup中的項賦值以后,我們還可以調用FormGroup的setValue方法來進行賦值操作。
比如當前我們對組件進行如下的初始化操作:
klass/edit/edit.component.ts
```
export class EditComponent implements OnInit {
formGroup: FormGroup;
private url: string; ①
constructor(private route: ActivatedRoute,
private router: Router,
private httpClient: HttpClient) {
}
private getUrl(): string { ②
return this.url;
}
/**
* 加載要編輯的班級數據
*/
loadData(): void {
this.httpClient.get(this.getUrl())
.subscribe((klass: Klass) => {
this.formGroup.setValue({name: klass.name, teacherId: klass.teacher.id}) ?;
}, () => {
console.error(`${this.getUrl()}請求發生錯誤`);
});
}
ngOnInit() {
this.formGroup = new FormGroup({
name: new FormControl(),
teacherId: new FormControl()
});
this.route.params.subscribe((param: { id: number }) => {
this.setUrlById(param.id);
this.loadData();
});
}
/**
* 用戶提交時執行的更新操作
*/
onSubmit(): void {
}
/**
* 設置URL請求信息
* @param {number} id 班級ID
*/
private setUrlById(id: number): void { ③
this.url = `http://localhost:8080/Klass/${id}`;
}
}
```
* ? 調用FormGroup的`setValue({})`來進行賦值操作。
## 獲取FormGroup的值
在數據提交時,需要獲取FormGroup的值,此時我們調用其`value`屬性。
klass/edit/edit.component.ts
```ts
/**
* 用戶提交時執行的更新操作
*/
onSubmit(): void {
const data = {
name: this.formGroup.value.name, ?
teacher: {id: this.formGroup.value.teacherId} ?
};
this.httpClient.put(this.getUrl(), data)
.subscribe(() => {
this.router.navigateByUrl('', {relativeTo: this.route});
}, () => {
console.error(`在${this.getUrl()}上的PUT請求發生錯誤`);
});
}
```
* ? 調用FormGroup的value屬性獲取當前表單的值
# 參考文檔
| 名稱 | 鏈接 | 預計學習時長(分) |
| --- | --- | --- |
| 源碼地址 | [https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step3.4.1](https://github.com/mengyunzhi/spring-boot-and-angular-guild/releases/tag/step3.4.1) | - |
| 把表單控件分組 | [https://www.angular.cn/guide/reactive-forms#grouping-form-controls](https://www.angular.cn/guide/reactive-forms#grouping-form-controls) | 10 |
| FormControlName | [https://www.angular.cn/api/forms/FormControlName](https://www.angular.cn/api/forms/FormControlName) | - |
| FormGroup | [https://www.angular.cn/api/forms/FormGroup](https://www.angular.cn/api/forms/FormGroup) | - |
- 序言
- 第一章: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
- 總結
- 開發規范
- 備用