在Angular中,可以使用Angular表单错误组件来在表单提交时触发验证。以下是一个示例解决方法:
import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent {
name: string;
email: string;
nameControl: FormControl;
emailControl: FormControl;
constructor() {
this.nameControl = new FormControl('', Validators.required);
this.emailControl = new FormControl('', Validators.required);
}
submitForm() {
if (this.nameControl.invalid || this.emailControl.invalid) {
// 在表单提交时触发验证
this.nameControl.markAsTouched();
this.emailControl.markAsTouched();
} else {
// 执行表单提交操作
console.log('Form submitted');
}
}
}
This field is required
Invalid email format
import { Component, Input } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-error-message',
templateUrl: './error-message.component.html',
styleUrls: ['./error-message.component.css']
})
export class ErrorMessageComponent {
@Input() control: FormControl;
}
通过以上步骤,你可以在表单提交时触发验证,显示错误消息,并执行相应的操作。