步骤1-注册ReactiveFormsModule
//app.module.ts
import {ReactiveFormsModule} from '@angular/core'
@NgModule({
imports:[
ReactiveFormsModule
]
})
步骤二-生成并导入一个新表单控件
//form.component.html
<form action="" [formGroup]="profileForm" (ngSubmit)="onSubmit()">
<label for="">
First Name:
<input type="text" formControlName="firstName" required>
</label>
<label for="">
Last Name:
<input type="text" formControlName="lastName">
</label>
<div formGroupName="address">
<h3>Address</h3>
<label for="">
Street:
<input type="text" formControlName="street">
</label>
<label for="">
city:
<input type="text" formControlName="city">
</label>
<label for="">
state:
<input type="text" formControlName="state">
</label>
<label for="">
zip:
<input type="text" formControlName="zip">
</label>
</div>
<button type="submit" [disabled]="!profileForm.valid">submit</button>
<button (click)="updateProfile()"></button>
</form>
//form.component.ts
import {Component,FormGroup,FormControl} from '@angular/core'
@Component({})
export class FormComponent {
profileForm = new FormGroup({
firstName:new FormControl(''),
lastName:new FormControl(''),
address:new FormGroup({
street:new FormControl('')
city:new FormControl('')
})
})
updateProfile(){
this.profileForm.patchValue({
firstName:'liang'
address:{
city:'beijing'
}
})
}
}
指令
- FormGroupDirective 把一个现有的FormGroup实例绑定到DOM元素
语法:
<form [formGroup]>...</form>
- FormGroupName 把一个内嵌胡FormGroup实例绑定到一个DOM元素
语法:
<form [formGroupName]="address">...</form>
- FormControlName 把一个现有 FormGroup 中的 FormControl 实例根据名字绑定到表单控件元素
语法:
<form [formControlName]="firstName">...</form>
方法 patchValue,setValue
- setValue 为单个控件设置新值,整体替换
- patchValue 用对象中所定义的任何属性对表单模型进行替换。
- patchValue 要针对表单模型的结构进行更新
formBuilder
代替手工创建FormGroup 和Formcontrol实例
注入依赖:
import {FormBuilder} from '@angular/core'
export class FormComponent{
profileForm = this.fb.group({
firstName:[''],
lastName:[''],
address:this.fb.group({
city:[''],
state:['']
})
})
constructor(private fb:FormBuilder){
}
}