Johnn
Johnn

Reputation: 57

Angular Tour of Heroes Master Details Explanation

I know this may sound strange to all of you but for some reason I don't know how to explain myself why this would work, I am probably missing something crucial.

So basically in angular-tour-of-heroes app, list of mock heroes is presented, you click on a hero inside of ngFor and selectedHero details is being shown.

Everything is fine because ngModel changes selectedHero variable inside typescript part as well as html part of the app.

But how can ngModel change 'hero' object inside ngFor loop? As I type in input field another hero name, the 'hero' from list from ngFor loop above changes as well. How does this work ?

Link: https://angular.io/tutorial/toh-pt2

heroes.component.html

<h2>My Heroes</h2>
<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>

<div *ngIf="selectedHero">

  <h2>{{selectedHero.name | uppercase}} Details</h2>
  <div><span>id: </span>{{selectedHero.id}}</div>
  <div>
    <label>name:
      <input [(ngModel)]="selectedHero.name" placeholder="name"/>
    </label>
  </div>

</div>

heroes.component.ts

export class HeroesComponent implements OnInit {
  heroes = HEROES

  selectedHero: Hero;

  onSelect(hero: Hero): void {
    this.selectedHero = hero
    console.log(this.selectedHero.name + ' here');
  }

  constructor() { }

  ngOnInit(): void {
  }

}

Upvotes: 0

Views: 209

Answers (2)

Oleksii Pavlenko
Oleksii Pavlenko

Reputation: 1333

Because on click you select hero and create object selectedHero that contains link into list of heroes that by nature list of objects . This question not about Angular, but more about nature of objects

For example

const a = { name: Alex }

const b = a;

b.name = “Tony”:

console.log(a.name) // will be Tony

Objects are mutable in JavaScript. As I told above, objects are reference typed data. Therefore, they contains the reference to the value. This reference points to the object’s memory location. The variables don’t actually contain the value. Keeping this in mind, let’s see what happens when we change the object value.

original object mutated

The reason behind this is — objects are reference type data. Whenever you create an object, it gets a new memory location. This memory location holds the object’s value. Then this memory location links to the variable name.

Upvotes: 2

Z. Bagley
Z. Bagley

Reputation: 9270

When a hero is clicked it runs the onSelect(hero) method.

this.selectedHero = hero; actually sets a pointer to the original location inside this.heroes. When your [(ngModel)] targets the selectedHero it's final destination targets the original hero in the ngFor. It is targeting the exact same variable as if I had an index in the array (e.g. const selectedHeroIndex) and [(ngModel)]="heroes[selectedHeroIndex"].

Upvotes: 1

Related Questions