0

我知道这对你们所有人来说可能听起来很奇怪,但由于某种原因,我不知道如何解释自己为什么这会起作用,我可能遗漏了一些重要的东西。

所以基本上在 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 {
  }

}
4

2 回答 2

2

因为单击时您选择 hero 并创建对象 selectedHero ,其中包含指向英雄列表的链接,该列表本质上是对象列表。这个问题不是关于 Angular,而是更多关于对象的性质

例如

const a = { name: Alex }

const b = a;

b.name = “Tony”:

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

JavaScript 中的对象是可变的。正如我上面所说的,对象是引用类型的数据。因此,它们包含对值的引用。该引用指向对象的内存位置。变量实际上并不包含值。记住这一点,让我们看看当我们改变对象值时会发生什么。

原始对象变异

这背后的原因是——对象是引用类型的数据。每当您创建一个对象时,它都会获得一个新的内存位置。此内存位置保存对象的值。然后这个内存位置链接到变量名。

于 2021-01-05T22:08:21.427 回答
1

当英雄被点击时,它会运行该onSelect(hero)方法。

this.selectedHero = hero;实际上设置了一个指向内部原始位置的指针this.heroes。当您的[(ngModel)]以 ngFor为目标时,selectedHero它的最终目标是针对herongFor 中原始目标。它的目标是完全相同的变量,就好像我在数组中有一个索引(例如 const selectedHeroIndex)和[(ngModel)]="heroes[selectedHeroIndex"].

于 2021-01-05T22:04:26.710 回答