我知道这对你们所有人来说可能听起来很奇怪,但由于某种原因,我不知道如何解释自己为什么这会起作用,我可能遗漏了一些重要的东西。
所以基本上在 angular-tour-of-heroes 应用程序中,会显示模拟英雄列表,您在 ngFor 中单击一个英雄,就会显示 selectedHero 的详细信息。
一切都很好,因为 ngModel 更改了 typescript 部分内的 selectedHero 变量以及应用程序的 html 部分。
但是 ngModel 如何在 ngFor 循环中更改“英雄”对象?当我在输入字段中输入另一个英雄名称时,上面 ngFor 循环列表中的“英雄”也会发生变化。这是如何运作的 ?
链接:https ://angular.io/tutorial/toh-pt2
hero.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>
hero.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 {
}
}