【问题标题】:Angular 12 FormsModule two way binding retains informationAngular 12 FormsModule 双向绑定保留信息
【发布时间】:2021-06-12 21:03:19
【问题描述】:

目前,我正在浏览 Angular 12.0.4 (https://angular.io/tutorial/toh-pt2) 的英雄教程。当我开始使用双向绑定表单时,我遇到了以下问题:

  1. 我点击一个英雄,将其选中
  2. 我更改了名称(在 FormsModule 中使用 2 向绑定)
  3. 我点击下一个英雄,改变选择的英雄
  4. 下一个英雄的名字变成了我之前选择的那个,失去了原来的“名字”数据

这是一个错误还是我应该如何修复我的代码?提前感谢您的建议。我在这里有一个工作流的 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;
  }

【问题讨论】:

标签: angular


【解决方案1】:

该错误已在 Angular v 12.0.5 中修复

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 2019-03-05
    • 2017-04-29
    • 1970-01-01
    • 2022-06-20
    • 1970-01-01
    • 2021-11-18
    相关资源
    最近更新 更多