1.首先寫數(shù)據(jù)模型
2伟桅,指令鏈接
<form [formGroup]="formModel" (submit)="onSubmit()">
<div>用戶名:<input type="text" name="username" formControlName="username"/></div>
<div formGroupName="passwordsGroup">
<div>密碼:<input type="text" name="password" formControlName="password"/></div>
<div>確認密碼:<input type="text" name="confirmpass" formControlName="confirmpass"/></div>
</div>
<div>電話:<input type="text" name="mobile" formControlName="mobile"/></div>
<div><input type="submit" value="提交"/></div>
</form>
export class ReactiveRegistComponent implements OnInit {
formModel: FormGroup;
constructor() {
this.formModel = new FormGroup({
username: new FormControl(),
mobile: new FormControl(),
passwordsGroup: new FormGroup({
password: new FormControl(),
confirmpass: new FormControl()
}),
password: new FormControl(),
confirmpass: new FormControl()
});
}
onSubmit() {
console.log(this.formModel.value);
}
ngOnInit() {
}
}
用FormBulider來配置一個表單模型比用new關(guān)鍵字實例化類,代碼少,fb.group相當于new 了一個group,可以接受另外一個參數(shù)击你,校驗玉组,用一個數(shù)組實例化formcontrol實例,第一個元素初始值丁侄,校驗方法惯雳,if的校驗方法。多于三個鸿摇,其他元素忽略石景。
export class ReactiveRegistComponent implements OnInit {
formModel: FormGroup;
constructor(fb: FormBuilder) {
this.formModel = fb.group({
/* username: new FormControl(),*/
username: [''],
mobile: [''],
passwordsGroup: fb.group({
password: [''],
confirmpass: ['']
}),
password: new FormControl(),
confirmpass: new FormControl()
});
}
onSubmit() {
console.log(this.formModel.value);
}
ngOnInit() {
}
}