我们可以使用FormControl来处理表单验证和错误消息。首先,确保你已经导入了FormsModule和ReactiveFormsModule模块。然后,创建一个FormControl对象并将其与表单控件绑定。最后,在HTML模板中,使用ngIf指令来显示错误消息。以下是示例代码:
在组件中:
import { Component } from '@angular/core'; import { FormControl, Validators } from '@angular/forms';
@Component({ selector: 'app-my-form', templateUrl: './my-form.component.html', styleUrls: ['./my-form.component.css'] }) export class MyFormComponent { username = new FormControl('', [Validators.required, Validators.minLength(4)]); }
在HTML模板中: