我可以轻松验证数组是否满足一些验证规则 . 当我想要与表单数组中的特定控件进行交互时,问题就变成了 .
我有包含表单组的表单数组 . 每个表单组都有几个表单控件 .
组看起来像这样:
const rowGroup = new FormGroup({
'range': new FormControl(row.range, [Validators.required, CustomValidators.range([1, 10000])]),
'multifamily': new FormControl(row.multifamily, [Validators.required, Validators.min(0), CustomValidators.range([0, 10000])]),
'office': new FormControl(row.office, [Validators.required, Validators.min(0), CustomValidators.range([0, 10000])]),
'retail': new FormControl(row.retail, [Validators.required, Validators.min(0), CustomValidators.range([0, 10000])]),
'other': new FormControl(row.other, [Validators.required, Validators.min(0), CustomValidators.range([0, 10000])])
});
表单数组包含组和 ascendingValidation
函数,它们进行验证 . 组是动态添加的,它们是无限的 .
const array = new FormArray([rowGroup], ascendingValidation);
在页面结果将是网格:
表格需要在“LTV范围顶部(%)”列上执行升序验证 .
示例(我总是谈论'LTV范围的顶部(%)'列):
-
第一种情况:如果用户将第一行中的值更改为44而不是41,则此字段(表单控件)将无效,因为用户按升序排序 . 我想仅在第一行显示错误消息,因为用户更改了该值 .
-
第二种情况:如果用户更改第二行并添加40而不是该字段需要无效 . 我想只显示第二行字段错误消息 .
-
第三种情况:如果用户用户在第一行添加45而不是41,则需要在该字段上显示错误消息 . 如果用户在第二行中添加46而不是43,则需要在第一行上删除错误,因为满足升序 .
PROBLEM:
我正在使用表单数组级别验证 . My problem is not how to implement algorithm to check is array ascending and which values are not in ascending order. This is easiest part .
在表单数组验证中,我可以在值发生更改时访问所有数组元素 . 实际上我不知道哪个控件最新改变了 .
How to detect which control caused value changes in form array validator?
Is there any better way to do this kind of validation?
1 回答
这是另一种可以帮助你的方法......我使用ngx-datatable为列模板提供了一个完整的api . 下面的逻辑跟踪上次更改的控件名称和行索引 .
我的表定义是
Note the formGroupName="details" which is a nested FormArray
我的专栏模板是这样的 .
在模板内部,我可以控制部分I显示视图或编辑部分..
Note the form group name, the index of the row been editing
在编辑部分内部,我展示了一个具有keydown事件的输入元素
Note: You can use the processInputKeyDown to track the last changed element.
我希望这可以帮到你 .