在Angular 7中,我们可以使用响应式表单来进行表单验证,其中包括“必填”验证。下面是一个示例解决方法:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
form: FormGroup;
constructor() { }
ngOnInit() {
this.form = new FormGroup({
name: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required, Validators.email]),
// 其他表单控件...
});
}
// 其他方法...
}
在上面的示例中,我们使用了Validators.required
来验证字段是否为必填项,并使用form.controls['name'].invalid
和form.controls['name'].errors.required
来显示错误消息。
这就是一个基本的Angular 7响应式表单中“必填”验证的解决方法。您可以根据您的需求进行修改和扩展。