dendimiiii
dendimiiii

Reputation: 1689

Angular4 compareWith function executing way too many times

I made a model driven form, with three formControls inside. two of them are initialized by null, and the last one is initialized with an object.

The values will change using a <select> tag of 50 items. The value will be of type Object. Internet told me that in case of an object value, I should use [compareWith] function, so i do.

actually, angular told me (see option caveat)

The first 2 ( initialized on null ) execute the compareWith function 50 times, as it should because there are 50 items to compare with.

The last (initialized with an object) executes this function 1000+(!!) times. What am I doing wrong? (See the console logs for the amount of executions)

Plunkr of doom

Edit: I also tried adding/removing null options. This causes weird execution times as well.

Plunkr2

Upvotes: 1

Views: 1705

Answers (1)

AVJT82
AVJT82

Reputation: 73337

I debugged this for a while and came to a conclusion :) One clue was the following statement from the link you shared. That is, that with compareWith...

We listen to the change event

So let's try and explain this behavior with your C option with object. compareWith is fired each time change happen, so naturally it will be fired when the array is modified. So it will be fired every time an item is "added" to your array on initialization:

// change happened in array

compare obj1 with our form control

// change happened in array

compare obj1, compare obj2 with form control

// change happened in array

compare obj1, compare obj2, compare obj3 with form control

and so it continues until we hit a match. The above would be without the null option you have in your select. But since you also have the [ngValue]="null" to compare with, this would be what is compared to our form control:

null, null, 01, null, 01, 02, null, 01, 02, 03, null ....

and so on..

So when each item will be added, the iteration of comparing will start all over again from the first item to the most latest added item.

As for why the two other only executes 50 times, is because, compareWith is fired 50 times, since list changes 50 times, but in this case, when compareWith is run it hits a match everytime because it's comparing null to null, where other is form control value and other is the null option value.


As to your other question, you don't need to use [compareWith], you can also just create a reference in another way. You mentioned in comment that you don't have an initial value to set when building the form, but when that object is available you can create a reference like:

this.form.patchValue({selectC: this.list.find(x => x.code == this.myObj.code)})

Now we do not need to worry about the amount of executions of compareWith :)

Upvotes: 2

Related Questions