我正在尝试将自定义验证器添加到我的 component.ts
自定义验证器文件:
import { FormGroup, ValidationErrors } from '@angular/forms';
export class ProfileCustomValidators {
static validateTime(fg: FormGroup): ValidationErrors {
const staffForm = fg.get('staffForm')
const fromTime = staffForm.get('fromTime').value;
const toTime = staffForm.get('toTime').value;
if(fromTime > toTime) {
return {
'endTime': {
message: 'End time should be greater than start time'
}
}
}
return null;
}
}
组件.ts
export class StaffFrom implements onInit {
staffForm: FormGroup;
constructor(private fb: FormBuilder){}
ngOnInit() {
this.staffForm = this.fb.group({
fromTime: new FormControl(null, Validators.required),
toTime: new FormControl(null, Validators.required),
}{ validator: ProfileCustomValidators.validateTime})
}
组件.html
<div>
<form [formGroup]="staffForm">
<mat-form-field>
<input
type="time"
required
formControlName="fromTime"
matInput
placeholder="From"
/>
</mat-form-field>
<mat-form-field>
<input
type="time"
required
formControlName="toTime"
matInput
placeholder="To"
/>
</mat-form-field>
</form>
</div>
通过使用上面的代码,我得到以下错误
Cannot read property 'get' of null
我需要一些帮助来解决这个问题,以及如何访问 custom.validator 文件中的 staffForm,因为它返回 null。谢谢你。