JacobTristan
JacobTristan

Reputation: 45

ngif comparing two arrays

I have two arrays in my component

arr1 = ["one", "two"]
arr2 = ["one", "two"]

In my html I am using my ngIf like this

*ngIf="!isEnabled && arr1 != arr2"

The isEnabled works fine but when comparing the two arrays it always shows that they are not equal even though they are set to be equal at the start.

The arr1 will change based on a service but I confirmed the service is changing the array already

Upvotes: 1

Views: 1364

Answers (2)

Aragorn
Aragorn

Reputation: 5289

just using != will always result in true because they are different objects, so never equal.

Unless they are two references to same array. Such as:

realArray = ['stuff'];

arr1 = realArray;
arr2 = realArray;

Assuming your arrays are two different objects, here're some ways you can use to compare arrays: How to compare arrays in JavaScript? ...

You are best to do it at the component in a function say compareArrays() and get a boolean response

*ngIf="!isEnabled && compareArrays()"

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222582

You actually cannot do this way, Instead of doing this comparision in template you should have a function that would return boolean value after comparing and then bind that to the template

*ngIf="!isEnabled && compareArrays()"

and

compareArrays(){
let result = array1.length == array2.length && 
    array1.every(function(element, index) {
    return element === array2[index]; 
});
return result;
}

Upvotes: 3

Related Questions