## FormGroup
追蹤一組`FormControl`實例的值和驗證狀態。
`FormGroup`聚合每一個子節點(`FormControl`)的值和驗證狀態到一個對象,并將控件名作為鍵值。通過逐步減少子節點狀態計算它自身狀態。例如:如果在`FormArray`中有一個子節點驗證失敗,那么最終整個對象驗證也會失敗。
`FormGroup`同`FormControl`及`FormArray`一同構成Angular表單3大基礎功能模塊。
### 使用方式
實例化`FormForm`,傳入一個子節點數組作為第1個參數,屬性名為每一個子節點要注冊的控件名。
```typescript
const form = new FormGroup({
first: new FormControl('Nancy', Validators.minLength(2)),
last: new FormControl('Drew'),
});
console.log(form.value); // {first: 'Nancy', last; 'Drew'}
console.log(form.status); // 'VALID'
```
You can also include group-level validators as the second arg, or group-level async validators as the third arg. These come in handy when you want to perform validation that considers the value of more than one child control.
```typescript
const form = new FormGroup({
password: new FormControl('', Validators.minLength(2)),
passwordConfirm: new FormControl('', Validators.minLength(2)),
}, passwordMatchValidator);
function passwordMatchValidator(g: FormGroup) {
return g.get('password').value === g.get('passwordConfirm').value
? null : {'mismatch': true};
}
```
### 添加或者移除控件
可以通過調用`FormArray`本身的`push`, `insert`或者`removeAt`方法來改變數組中的控件。這些方法能夠保證在表單層級樹中控件狀態能夠合理的被跟蹤到。不建議直接修改`FormArray`中的`AbstractControl`實例,因為它會導致一些奇怪和無法預期的行為,例如打斷Angular的值檢測。
### Class
```typescript
class FormGroup {
constructor(controls: {[key: string]: AbstractControl}, validator?: ValidatorFn, asyncValidator?: AsyncValidatorFn)
controls : {[key: string]: AbstractControl}
registerControl(name: string, control: AbstractControl) : AbstractControl
addControl(name: string, control: AbstractControl) : void
removeControl(name: string) : void
setControl(name: string, control: AbstractControl) : void
contains(controlName: string) : boolean
setValue(value: {[key: string]: any}, {onlySelf}?: {onlySelf?: boolean}) : void
patchValue(value: {[key: string]: any}, {onlySelf}?: {onlySelf?: boolean}) : void
reset(value?: any, {onlySelf}?: {onlySelf?: boolean}) : void
getRawValue() : Object
}
```
### 屬性
- controls : `AbstractControl[]` 包含的控件集合
- registerControl(name: `string`, control: `AbstractControl`) : `AbstractControl` 在當前控件所屬對象中注冊一個新的控件。該方法并不會更新控件的值和驗證狀態,因此大多數情況下最好使用`addControl`來創建新的控件。
- addControl(name: `string`, control: `AbstractControl`) : `void` 在當前對象中添加一個新的控件。
- removeControl(name: `string`) : `void` 從當前對象中移除一個控件。
- setControl(controlName: `string`, control: `AbstractControl`) : `void` 替換已存在的控件
- contains(controlName: `string`) : `boolean` 在當前對象中檢查是否存在給定名稱的已激活控件。對于禁用的控件它將返回`false`, 如果需要檢查控件是否存在,請使用`get`方法。
- setValue(value: {[key: `stirng`]: `any`}, {onlySelf}?: {onlySelf?: `boolean`}) : `void` 設置`FormGroup`的值。接收一個以控件名為屬性,并且滿足group格式的對象。
該方法會執行嚴格檢查,即如果嘗試傳遞一個不存在或被移除的控件,它會直接拋出錯誤。
```typescript
const form = new FormGroup({
first: new FormControl(),
last: new FormControl()
});
console.log(form.value); // {first: null, last: null}
form.setValue({first: 'Nancy', last: 'Drew'});
console.log(form.value); // {first: 'Nancy', last: 'Drew'}
```
- patchValue(value: {[key: `stirng`]: `any`}, {onlySelf}?: {onlySelf?: `boolean`}) : `void` 填充`FormGroup`對象的值,同樣接收一個以控件名為屬性,并且滿足group格式的對象,不同的是它會盡量把傳入的參數匹配到正確控件。它可以接收上一級或者子集對象,而不會報錯。
```typescript
const form = new FormGroup({
first: new FormControl(),
last: new FormControl()
});
console.log(form.value); // {first: null, last: null}
form.patchValue({first: 'Nancy'});
console.log(form.value); // {first: 'Nancy', last: null}
```
- reset(value?: `any`, {onlySelf?}: {onlySelf?: `boolean`}) : `void` 重置`FormGroup`值。
You can also reset to a specific form state by passing in a map of states that matches the structure of your form, with control names as keys. The state can be a standalone value or a form state object with both a value and a disabled status.
```typescript
this.form.reset({first: 'name', last; 'last name'});
console.log(this.form.value); // {first: 'name', last: 'last name'}
```
或者:
```typescript
this.form.reset({
first: {value: 'name', disabled: true},
last: 'last'
});
console.log(this.form.value); // {first: 'name', last: 'last name'}
console.log(this.form.get('first').status); // 'DISABLED'
```
- getRawValue() : `any[]` 獲取`FormGroup`數組的聚合值,包含任何被禁用的控件。
如果想獲取所有值包括被禁用的狀態,請使用此方法。否則,使用`value`屬性是最好獲取數組中值的方式。
- 說明
- angular 1.x
- ngModelController
- ngOptions
- ngModelOptions
- lifecycle
- directive
- angular 2
- @angular/forms
- 類
- AbstractControl
- AbstractControlDirective
- AbstractFormGroupDirective
- FormControl
- FormArray
- FormBuilder
- FormGroup
- NgControl
- 接口
- controlValueAccessor
- 指令
- DefaultValueAccessor
- Angular 2 生命周期
- OnInit
- DoCheck
- @angular/router
- 配置
- Routes
- 指令
- RouterOutlet
- RouterLink
- 接口
- ActivatedRoute
- UrlTree
- NavigationExtras
- ActivatedRouteSnapshot
- RouterStateSnapshot
- 類
- UrlSegment
- UrlSegmentGroup
- UrlSerializer
- DefaultUrlSerializer
- Router
- bug記得
- @angular/http
- 類
- Http
- Body
- Response
- ResponseOptions
- Header
- Request
- RequestOptions
- URLSearchParams
- @angular/core
- decorator
- Component-decorator
- animation
- DI
- linker
- TemplateRef
- ElementRef
- EmbeddedViewRef
- ViewRef
- ViewContainerRef
- Query
- ComponentFactory
- ComponentRef
- Renderer
- change_detection
- KeyValueDiffers
- IterableDiffers
- ChangeDetectorRef
- ChangeDetectionStrategy
- Zone
- ngZone
- @angular/common
- 指令
- NgTemplateOutlet
- QueryList
- bootstrap4
- card
- form
- 重點關注博客
- 學習過的文章
- 筆記
- Angular 2 雙向綁定
- 將字符串解析成DOM
- rx相關
- operators
- combineLatest
- combineAll
- concat(All, Map, *MapTo)
- 背壓(backpressure)
- js事件keycode對應表
- 裝飾器
- 有用的代碼摘錄
- 日期操作
- 數量操作
- 字符操作
- rxjs問題
- 小示例
- h5面試準備
- react
- 開發遇到的問題