要解决Angular 8 / Material中子表单不显示错误的问题,可以按照以下步骤进行操作:
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
FormGroup
和FormControl
来实现这一点。在组件的类中添加以下代码:import { Component } 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 YourComponentComponent {
parentForm: FormGroup;
constructor() {
this.parentForm = new FormGroup({
childForm: new FormGroup({
firstName: new FormControl('', Validators.required),
lastName: new FormControl('', Validators.required)
})
});
}
get childForm() {
return this.parentForm.get('childForm');
}
onSubmit() {
if (this.parentForm.valid) {
console.log('Form submitted successfully');
} else {
console.log('Form has errors');
}
}
}
formGroup
指令来绑定父表单,并使用formGroupName
指令来绑定子表单。添加以下代码:
在上面的代码中,我们使用了mat-error
元素来显示表单验证错误信息。通过检查childForm.get('fieldName').invalid
和childForm.get('fieldName').touched
属性,我们可以判断字段是否存在错误,并且用户是否已经触摸过它。
FormsModule
,ReactiveFormsModule
,MatInputModule
和MatFormFieldModule
。在NgModule的imports
数组中添加以下代码:@NgModule({
imports: [
// ...
FormsModule,
ReactiveFormsModule,
MatInputModule,
MatFormFieldModule
],
// ...
})
export class YourModule { }
这样就完成了子表单不显示错误的解决方法。当用户在子表单中输入错误时,相应的错误信息将被显示出来。