在模板中添加一个包裹表单的DIV,并使用FormControlName将每个表单元素与组件中的FormControl进行绑定。然后,为该DIV添加一个键盘事件监听器,以便在用户按回车键时执行表单提交操作。在提交之前,您可以添加必要的验证逻辑以确保用户输入有效。
示例代码如下所示:
在组件中,需要初始化myForm并在onFormSubmit()方法中提交表单。您可以根据需要添加其他验证逻辑。
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html',
styleUrls: ['./my-form.component.css']
})
export class MyFormComponent implements OnInit {
myForm: FormGroup;
ngOnInit(): void {
this.myForm = new FormGroup({
email: new FormControl('', Validators.required),
password: new FormControl('', Validators.required)
});
}
onFormSubmit(): void {
if (this.myForm.valid) {
// Submit the form
}
}
}