Hello everyone, this is my first post here. I have been diving into the Angular Tour of Heroes using Angular 6 and I think I understand how ngModel works, but there's one thing that puzzles me. How does it manage to update the data in my list when the ngModel is linked to a different variable? Below is the code snippet that has been causing some confusion:
The heroes variable holds a list of mock data with each item having a type defined as Hero, consisting of an ID and a name.
A list of heroes is displayed through the use of a variable called hero.
Whenever a hero is clicked, the variable selectedHero is set to that specific Hero object.
Following this selection, the details of the chosen hero are shown below the list.
I comprehend that any changes made to selectedHero.name by using ngModel on the input field also affect the corresponding hero's name in the list. But, I am uncertain about how to prevent this auto-update from happening.
P.S. Since I'm new here, I couldn't locate any answers related to this issue. Apologies if this post isn't in the right place.
heroes.component.html
<h2>My Heroes</h2>
<ul class="heroes">
<!--calls function when selected and changes the background color to the selected class-->
<li *ngFor="let hero of heroes"
(click)="onSelect(hero)"
[class.selected]="hero === selectedHero">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</li>
</ul>
<div *ngIf="selectedHero">
<h2>{{ selectedHero.name }}</h2>
<div>id: {{ selectedHero.id }}</div>
<div>
<label>name:
<input [(ngModel)]="selectedHero.name" placeholder="Hero Name">
</label>
</div>
</div>
heroes.component.ts
import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HEROES } from '../mock-heroes';
@Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
heroes = HEROES;
selectedHero: Hero; // undefined until selected
onSelect(hero: Hero) {
this.selectedHero = hero;
}
constructor() { }
ngOnInit() {
}
}