0

I have two different dropdowns (implemented a as a cihld components) with the same data inside.

I want to display mat-error if those two selected values are the same. On a mat-error tag, I call a function:

areValuesTheSame() {
  if (this.form.controls['value1'].value && this.form.controls['value2'].value) {
      return this.form.controls['value1'].value === this.form.controls['value2'].value;
}

I thought that I will get the result true/false and according to that in a mat-error I will do like this:

<mat-error *ngIf="areValuesTheSame()">Selected values has to be the same!</mat-error>

But the thing is, that it constantly returns the values for me instead of returning it one time (true or false).

If I try to check it in the console.log, the console prints the result n times (like an infinite loop).

What I'm doing wrong here?

HELPME
  • 714
  • 14
  • 35
  • where do u put your console.log? – Ala Abid May 23 '19 at 10:09
  • I put my console.log instead of "return" to see how it actually works. – HELPME May 23 '19 at 10:13
  • 1
    The "proper" Angular way would be to make `areValuesTheSame` a validator (it'll run when something happens to inputs, not on every change detection). https://angular.io/guide/form-validation – mbojko May 23 '19 at 10:19

2 Answers2

1

Actually its nothing wrong with your code. Its how Angular works. It runs change detection automatically, and when changes are checked it runs your function.

Check this: angular2 - infinite loop when i call method from a Angular 2 class inside template

porgo
  • 1,729
  • 2
  • 17
  • 26
0

Your function is called on every change detection cycle, to avoid that behavior, put a boolean inside your *ngIf and change it on value change of your value1 and value2, for example, on a (keyup) event

<input formControlName="value1" (keyup)="areSame()" />
<input formControlName="value2" (keyup)="areSame()" />
<mat-error *ngIf="!sameBool">Selected values has to be the same!</mat-error>

TS:

areSame(){
 if(this.form.controls['value1'].value === this.form.controls['value2'].value)
   sameBool= true;
}

EDIT: using Validators as mentioned in the comments is even better.

Ala Abid
  • 2,256
  • 23
  • 35