Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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([])
        });
like image 859
nilanjan Avatar asked Mar 03 '17 08:03

nilanjan


People also ask

How do you know if reactive form value is changed?

You can use rxjs operators to check values.


2 Answers

console.log(!!this.myForm.get('mycontrol').value);
like image 189
Günter Zöchbauer Avatar answered Nov 15 '22 03:11

Günter Zöchbauer


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.

like image 23
peregrination Avatar answered Nov 15 '22 03:11

peregrination