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

时间:2017-03-03 08:07:15

标签: angular typescript

我有一个表格,其中有4-5种不同类型的控制。 在某些用户操作中,我需要知道任何控件是否具有任何值,并且它可以在窗体的任何状态上发生 - 无论是原始还是脏。我不能依赖于形式状态。 因为this.myForm.controls不是一个数组类型,所以c甚至可以循环遍历。此外,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([])
        });

3 个答案:

答案 0 :(得分: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();

}

这将遍历表单组并检查每个控件的有效值,然后您可以在这些情况下执行所需的操作。

希望它有所帮助。

答案 1 :(得分:0)

console.log(!!this.myForm.get('mycontrol').value);

答案 2 :(得分:0)

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

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

这将检查value对象中代表表单状态的属性,如果其中任何一个属性为真,即具有值,则返回true