1.在组件中引入FormsModule和ReactiveFormsModule
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
// other imports ...
FormsModule,
ReactiveFormsModule
],
})
export class YourModule { }
2.在组件中初始化表单
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl('')
});
ngOnInit() { }
}
3.在HTML中显示表单
4.在组件中处理提交逻辑
onSubmit() {
// TODO: Use EventEmitter with form value
console.warn(this.profileForm.value);
}
这样,当用户提交表单时,将会调用onSubmit()方法提交表单的值。 您可以在该方法中将值发送到服务器,或在页面上显示成功消息。