1st post here. So I am following the Angular Tour of heroes using Angular 6 and I get how ngModel is working.. for the most part. I just don't get how it is able to change my data in the list when the ngModel is assigned a different variable. Here is my code below:
heroes is assigned list of mock data with a Hero type consisting of ID and name.
This is showing a list of heroes through a variable called hero
When a hero is clicked, selectedHero is assigned a Hero.
From there a the details of a hero is displayed underneath the list.
I understand that when using ngModel in the input changes the selectedHero.name, but how is it able to change the the hero.name in the list and how would I be able to stop it from changing that?
ps, I'm new here, I could not find anything that could answer this. So apologies if I posted this in the wrong 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() {
}
}
selectedHero
is nothing but a pointer to an element in your list. If you don't want it to be changed, you probably shouldn't useselectedHero.name
in your model, but something else, e.g.public String selectedHeroName;
– Jan B.