【发布时间】:2021-06-12 21:03:19
【问题描述】:
目前,我正在浏览 Angular 12.0.4 (https://angular.io/tutorial/toh-pt2) 的英雄教程。当我开始使用双向绑定表单时,我遇到了以下问题:
- 我点击一个英雄,将其选中
- 我更改了名称(在 FormsModule 中使用 2 向绑定)
- 我点击下一个英雄,改变选择的英雄
- 下一个英雄的名字变成了我之前选择的那个,失去了原来的“名字”数据
这是一个错误还是我应该如何修复我的代码?提前感谢您的建议。我在这里有一个工作流的 gif:Example
问题出现在带有谷歌浏览器的 WSL 中的 Ubuntu 上。我无法使用完全相同的代码在 stackblitz 中重现此错误。 Edge 中也不会出现此问题。
heroes.compontent.html:
<table class='table table-hover'>
<thead>
<th scope="col">#</th>
<th scope="col">Name</th>
</thead>
<tbody>
<ng-container *ngFor="let hero of heroes">
<tr (click)="onSelect(hero)" [class.table-active]="hero === selectedHero">
<th scope="row">{{hero.id}}</th>
<td>{{hero.name}}</td>
</tr>
</ng-container>
</tbody>
</table>
<div *ngIf="selectedHero">
<h2>{{selectedHero.name | uppercase}} Details</h2>
<div><span>id: </span>{{selectedHero.id}}</div>
<div>
<label for="hero-name">Hero name: </label>
<input id="hero-name" [(ngModel)]="selectedHero.name" placeholder="name">
</div>
</div>
heroes.component.ts:
import { Component, OnInit } from '@angular/core';
import { Hero } from './hero'
@Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.scss']
})
export class HeroesComponent implements OnInit {
heroes: Hero[] = [
{ id: 11, name: 'Dr Nice' },
{ id: 12, name: 'Narco' },
{ id: 13, name: 'Bombasto' },
{ id: 14, name: 'Celeritas' },
{ id: 15, name: 'Magneta' },
{ id: 16, name: 'RubberMan' },
{ id: 17, name: 'Dynama' },
{ id: 18, name: 'Dr IQ' },
{ id: 19, name: 'Magma' },
{ id: 20, name: 'Tornado' }
];
selectedHero?: Hero;
constructor() { }
ngOnInit(): void {
}
onSelect(hero: Hero): void {
this.selectedHero = hero;
}
}
hero.ts:
export interface Hero {
id: number;
name: string;
}
【问题讨论】:
-
尝试在 Stackblitz 上重现您的代码,但似乎无法重现此行为? stackblitz.com/edit/angular-ivy-pqvcut?file=src/app/…
-
奇怪,当我将所有代码放在那里时,我也无法重现它。 (stackblitz.com/edit/angular-bug-heroes-t) 可能是客户端使用 npm 出错...
-
很难说,我猜。你的代码看起来也是正确的...... :)
标签: angular