Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

*ngFor object comparison using '==='

Going through the Angular tutorial (Tour of Heroes), I've stumbled upon a comparison between two objects. Since this is not a common practice I've tried multiple comparisons inside the class and all returned false, except if the compared are hero[0] and selectedHero, the returned value is true, assuming we assigned selectedHero with hero[0].

Tour of Heores part of code where comparison occurs: Link to StackBlitz

<ul class="heroes">
  <li *ngFor="let hero of heroes"
    [class.selected]="hero === selectedHero"
    (click)="onSelect(hero)">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
  </li>
</ul>

Why is this comparison returning true? What exactly is being compared here? I haven't found any explanation yet.

like image 913
Polkovnik Avatar asked Apr 18 '26 06:04

Polkovnik


1 Answers

=== is checking the value (if the subject is a number or a boolean), the type and the object reference. If you create 2 objects with identical attributes like the following, it will return false :

let a = { test: 'test' };
let b = { test: 'test' };
console.log(a === b); // gives false

because it's not the same reference. So in your case, selectedHero === hero will be true if your 2 objects has the same reference.

EDIT :

Another precision is that you can copy object reference in another :

let a = { test: 'test' };
let b = a;
console.log(a === b); // gives true

and then if you change attribute of one the reference, it will change for both :

let a = { test: 'test' };
let b = a;
a.test = 'foo';
console.log(b.test) // gives foo
like image 186
Julien METRAL Avatar answered Apr 20 '26 23:04

Julien METRAL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!