- 在组件的相应视图中添加表单元素,例如:
- 在组件的typescript文件中,在需要的部分引入表单相关模块,例如
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
- 创建表单控制组:
export class MyFormComponent implements OnInit {
myForm: FormGroup;
constructor() { }
ngOnInit() {
this.myForm = new FormGroup({
name: new FormControl('', [
Validators.required,
Validators.minLength(2),
Validators.maxLength(20),
]),
password: new FormControl('', [
Validators.required,
Validators.minLength(6),
Validators.maxLength(30),
]),
});
}
- 在组件的typescript文件中,为表单元素创建提交函数:
onSubmit() {
console.log(this.myForm.value); // 表单数据打印到控制台
}
- 修改表单元素,将它们绑定到表单控制组的表单控件对象上: