nilanjan
nilanjan

Reputation: 179

How to check if any control in a reactive form has value in Angular 2

I have a form in which there are 4-5 different types of control. On certain user action, I need to know if any of the controls have any value in it and it can happen on any state of the form - be it pristine or dirty. I cannot rely on the form states for this. cCan't even loop through since this.myForm.controls isn't an array type. Also this.myForm.value is always an 'object' even though no values for controls in it.

Here is the form creation code, if that helps:

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([])
        });

Upvotes: 13

Views: 33228

Answers (4)

Jofred Reinosa
Jofred Reinosa

Reputation: 89

This could be a way to do that, even if you have nested forms.

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.checkIfFormHasAnyValidValue(control);
  }
});
return hasValidValues;

}

Upvotes: 1

peregrination
peregrination

Reputation: 2638

Here's a quick way you can do this check using Object.keys().

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

This will check the properties in the value object that represents your form state, and return true if any of those properties are truthy, i.e. have a value.

Upvotes: 6

UofABBallCoder626
UofABBallCoder626

Reputation: 84

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();

}

This will loop through a form group and check the valid values of each control, then you can do what you want with them in the cases.

Hope it helps.

Upvotes: 1

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657308

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

Upvotes: 8

Related Questions