在Angular中,你可以使用FormControl
来创建一个响应式表单控件,并在失焦时进行验证,但在输入时更新模型。下面是一个示例解决方法:
首先,在你的组件中引入所需的模块和类:
import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
然后,在组件类中定义一个FormControl
对象,并设置验证规则和初始值:
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
inputControl: FormControl;
ngOnInit() {
this.inputControl = new FormControl('', Validators.required);
}
}
接下来,在模板中使用ngModel
指令将输入框与FormControl
绑定,并添加blur
事件来触发失焦时的验证:
最后,在模板中添加一个显示验证错误信息的元素:
此字段不能为空
现在,当用户输入内容时,模型会自动更新。当输入框失焦时,将触发验证,并显示相应的错误信息。
请注意,以上示例假设你已经在app.module.ts
中导入了FormsModule
和ReactiveFormsModule
。