如何检查反应式形式的任何控件在 Angular 2 中是否有价值

问题描述 投票:0回答:4

我有一个表单,其中有 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([])
        });
angular typescript
4个回答
7
投票
console.log(!!this.myForm.get('mycontrol').value);

6
投票

这是一种使用 Object.keys() 进行此检查的快速方法。

Object.keys(this.searchForm.value).some(k => !!this.filterForm.value[k])

这将检查代表表单状态的

value
对象中的属性,如果这些属性中有任何一个为真(即具有值),则返回
true


1
投票
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();

}

这将循环遍历表单组并检查每个控件的有效值,然后您可以在情况下对它们执行您想要的操作。

希望有帮助。


0
投票

即使您有嵌套表单,这也可能是一种方法。

checkIfFormHasAnyValidValue(formGroup: UntypedFormGroup): boolean {
let hasValidValues = false;
Object.keys(formGroup.controls).forEach((field) => {
  const control = formGroup.get(field);
  if (control instanceof UntypedFormControl) {
    if (control.valid) {
      hasValidValues = true;
    }
  } else if (control instanceof UntypedFormGroup) {
    this.validateForm(control);
  }
});
return hasValidValues;

}

© www.soinside.com 2019 - 2024. All rights reserved.