问题是即使我将字段留空并移至另一个字段,也不会显示错误消息。我无法找到我在这里做错了什么。任何帮助将不胜感激。如果我在 onFormValuesChanged() 上放置断点,它永远不会到达断点。我尝试过在构造函数内移动表单的构建部分,但没有任何影响。我不确定当字段值更改时是否触发表单的值更改事件
角度版本:- 5.2.1
HTML 代码
<div>
<form [formGroup]="formPersonalRecord">
<mat-input-container class="full-width-input">
<input matInput placeholder="First Name" formControlname="firstName">
<mat-error *ngIf="formErrors.firstName.required">
Please provide name.
</mat-error>
</mat-input-container>
<mat-input-container class="full-width-input">
<input matInput placeholder="Last Name" formControlname="lastName">
</mat-input-container>
<mat-input-container class="full-width-input">
<input matInput placeholder="Father's Name" formControlname="fatherName">
</mat-input-container>
<mat-input-container class="full-width-input">
<input matInput placeholder="Email" formControlname="email">
<mat-error *ngIf="formErrors.email.required">
Please provide a email name.
</mat-error>
</mat-input-container>
</form>
</div>
组件.cs
import { Component, OnInit } from '@angular/core';
import { EmployeePersonalRecord } from '../employee/employee-personal-record';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { fuseAnimations } from '../../core/animations';
import { HrService } from '../hr.service';
@Component({
// tslint:disable-next-line:component-selector
selector: 'app-add-employee',
templateUrl: './add-employee.component.html',
styleUrls: ['./add-employee.component.scss'],
animations: fuseAnimations
})
export class AddEmployeeComponent implements OnInit {
employeePersonalRecord: EmployeePersonalRecord = {} as EmployeePersonalRecord;
public formPersonalRecord: FormGroup;
formErrors: any;
constructor(private builder: FormBuilder,
private service: HrService) {
}
onFormValuesChanged()
{
for ( const field in this.formErrors )
{
if ( !this.formErrors.hasOwnProperty(field) )
{
continue;
}
// Clear previous errors
this.formErrors[field] = {};
// Get the control
const control = this.formPersonalRecord.get(field);
if ( control && control.dirty && !control.valid )
{
this.formErrors[field] = control.errors;
}
}
}
ngOnInit() {
this.formPersonalRecord = this.builder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
email: ['', Validators.required],
fatherName: ['', Validators.required],
dateOfBirth: ['', Validators.required],
addressPermanent: ['', Validators.required],
addressCurrent: ['', Validators.required],
gender: ['', Validators.required],
maritalStatus: ['', Validators.required],
religion: ['', Validators.required],
cast: ['', Validators.required]
});
this.formErrors = {
firstName: {},
lastName: {},
email: {},
fatherName: {},
dateOfBirth: {},
addressPermanent: {},
addressCurrent: {},
gender: {},
maritalStatus: {},
religion: {},
cast: {}
};
this.formPersonalRecord.valueChanges.subscribe(() => {
this.onFormValuesChanged();
});
}
}