我有一个在“ngOnInit”事件中调用的方法:
public form!: FormGroup;
initForm(calendar?: Calendar) {
const baseForm = this.fb.group({
[FORM_INPUT.START_DATE]: [{
value: calendar && this.isSomeCardSelected ? calendar.startDate : '',
disabled: false,
}, [this.customValidationsService.dateValidator()]],
[FORM_INPUT.END_DATE]: [{
value: calendar && this.isSomeCardSelected ? calendar.endDate : '',
disabled: false,
}, [this.customValidationsService.dateValidator()]],
});
if (this.isDateStartHiring) {
//The code that adds the new field "START_DATE_HIRING" should go right here. I tried it in several ways, but when I execute the form it keeps launching the date validation, which is fine for me to launch, but it should be null and not show any error.
}
this.form = baseForm;
this.cdr.detectChanges();
this.initFormSubscriptions();
}
我需要动态添加一个新字段(
isDateStartHiring
此变量设置为 true,只需从下拉列表中选择特定选项即可):
[FORM_INPUT.START_DATE_HIRING]: [{value: calendar && calendar.startContractDate &&
this.isSomeCardSelected ? calendar.startContractDate : '', disabled: false}, [this.customValidationsService.dateValidator()]],
});]],
这是验证器方法:
public dateValidator(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
const value = control.value;
if (!(value instanceof Date) || isNaN(value.getTime())) {
if (value === '') return {dateRequired: true};
return {dateValidator: true};
}
return null;
};
}
我想动态添加它,因为当我按下保存按钮时,我会得到验证: this.customValidationsService.dateValidator() 尽管所有 3 个日期字段都有一个默认值,即每个字段的状态都是 false,因此这个 .form 的值.valid 也是 false 并且不访问 if,如果字段已填充,则表单的状态应该为 true:
submit() {
if(this.form.valid) {
}
出现此问题的原因是我从下拉菜单中选择了不同的选项:其中 3 个选项具有 2 个字段 START_DATE 和 END_DATE,而第 4 个选项是维护 2 个字段并添加 START_DATE_HIRING 的选项,但该选项不起作用。
什么类型
this.isDateStartHiring
变量是?如何将其设置为 false 或 true?检查设置是否有效。
您可以根据 isDateStartHiring 变量使用 FormGroup 中的 addControl 或 removeControl 方法。