我有一个表单,其中有4-5种不同类型的控制。对于特定的用户操作,我需要知道是否有任何控件在其中有任何值,并且它可以发生在表单的任何状态上-无论是原始的还是脏的。对于这一点,我不能依赖表单状态。C甚至不能循环遍历,因为this.myForm.controls不是数组类型。此外,this.myForm.value始终是一个“对象”,即使其中没有控件的值。
下面是表单创建代码,如果有帮助的话:
this.searchForm = this.fb.group({
'ids': this.fb.control([], multipleInputValidator(2)),
'locationName': this.fb.control([], Validators.minLength(2)),
'accountCodes': this.fb.control([], multipleInputValidator(2)),
'regionCodes': this.fb.control([], multipleInputValidator(2)),
'city': this.fb.control([], Validators.minLength(2)),
'typeIds': this.fb.control([]),
'centreIds': this.fb.control([]),
'siteCodes': this.fb.control([]),
'statusCode': this.fb.control([]),
'from': this.fb.control([]),
'to': this.fb.control([])
});发布于 2017-03-03 16:09:16
console.log(!!this.myForm.get('mycontrol').value);发布于 2017-03-08 01:31:09
checkFormChanges() {
this.searchForm.valueChanges
.filter(() => this.searchForm.valid)
.map((value) => {
for (let key in value) {
if (value[key]) {
switch (key) {
case 'whatever': //do something
}
}
}
}).subscribe();}
这将遍历一个表单组并检查每个控件的有效值,然后您可以在案例中对它们执行您想要的操作。
希望能有所帮助。
发布于 2020-10-10 02:25:47
以下是使用Object.keys()执行此检查的一种快速方法。
Object.keys(this.searchForm.value).some(k => !!this.filterForm.value[k])这将检查表示表单状态的value对象中的属性,如果这些属性中的任何一个为真,即具有值,则返回true。
https://stackoverflow.com/questions/42573661
复制相似问题