一、响应式表单提交
1.1 使用 FormGroup实例
1.1.1 在app.module.ts中引入 ReactiveFormsModule
import { ReactiveFormsModule } from '@angular/forms'
1.1.2 创建表单
<!-- 通过 ngSubmit 会监控这个表单发送出来的submit值 -->
<form [formGroup]="profileForm" (submit)="onSubmit()">
<label>
First Name:
<input type="text" formControlName="firstName">
</label>
<br />
<label>
Last Name:
<input type="text" formControlName="lastName" placeholder="请输入last name">
</label>
<div formGroupName="addressForm">
<label>
street:
<input type="text" formControlName="street">
</label>
<br/>
<label>
city:
<input type="text" formControlName="city">
</label>
<br/>
<label>
state:
<input type="text" formControlName="state">
</label>
<br/>
<label>
zip:
<input type="text" formControlName="zip">
</label>
<br/>
</div>
<button type="submit" [disabled]="!profileForm.valid">submit</button>
</form>
1.1.3 进行绑定
import { FormGroup, FormControl } from '@angular/forms';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-product-groupEditor',
templateUrl: './product-groupEditor.component.html',
styleUrls: ['./product-groupEditor.component.css']
})
export class ProductGroupEditorComponent implements OnInit {
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
addressForm: new FormGroup({
street: new FormControl(''),
city: new FormControl(''),
state: new FormControl(''),
zip: new FormControl('')
})
});
constructor() { }
ngOnInit() {
}
onSubmit() {
console.warn(this.profileForm.value);
window.alert(this.profileForm.value);
// this.profileForm.reset();
this.profileForm.setValue({
firstName: 'Nancy'
})
// this.profileForm.setValue({firstName:"tomtom"});
}
}
1.2 使用FormBuilder创建表单
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder } from '@angular/forms'
@Component({
selector: 'app-product-builderEdit',
templateUrl: './product-builderEdit.component.html',
styleUrls: ['./product-builderEdit.component.css']
})
export class ProductBuilderEditComponent implements OnInit {
checkoutForm = this.formBuilder.group({
firstName: [''],
lastName: [''],
addressForm: this.formBuilder.group({
street: [''],
city: [''],
state: [''],
zip: ['']
})
});
constructor(
private formBuilder : FormBuilder
) { }
ngOnInit() {
}
onSubmit() {
console.warn(this.checkoutForm.value);
window.alert(this.checkoutForm.value);
// this.profileForm.reset();
this.checkoutForm.patchValue({
firstName: 'Nancy'
})
// this.profileForm.setValue({firstName:"tomtom"});
}
}