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 {
}
}
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
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.