这是Hero的界面
export interface Hero {
id: number,
name: string
}英雄名单
import { Hero } from './model-interfaces/hero';
export const HEROS: Hero[] = [
{ id: 12, name: 'Dr. Nice' },
{ 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' }
];英雄的组成部分
export class HerosComponent implements OnInit {
heros = HEROS;
selectedHero?: Test;
constructor() { }
ngOnInit(): void {
}
onSelect(hero: Test): void {
this.selectedHero = hero;
}
}英雄列表的HTML
<h2>My Heroes</h2>
<ul class="heroes">
<li *ngFor="let hero of heros">
<button [class.selected]="hero === selectedHero" type="button" (click)="onSelect(hero)">
<span class="badge">{{hero.id}}</span>
<span class="name">{{hero.name}}</span>
</button>
</li>
</ul>
<app-hero-details [hero] = "selectedHero"></app-hero-details>获得选定的英雄
export class HeroDetailsComponent implements OnInit {
@Input() hero?: Hero
constructor() { }
ngOnInit(): void {
}
}选定英雄的HTML
<div *ngIf="hero">
<h2>{{hero.name | uppercase}} Details</h2>
<div>ID: {{hero.id}}</div>
<div>
<label for="hero-name">Hero name: </label>
<input id="hero-name" [(ngModel)]="hero.name" placeholder="name">
</div>在这里,当我从英雄名单中选择一个英雄时。选定的英雄将显示在页面底部的文本框中。当我在文本框中更改选定的英雄时,我不知道为什么列表中选定的英雄会被更改。
因为选定的英雄存储在一个单独的变量中。如何更改“英雄”列表中选定的“英雄”?
发布于 2022-06-27 12:32:06
,因为选定的英雄存储在单独的变量中。
由于英雄是对象,因此单独的变量实际上只是对内存中相同对象的另一个引用。考虑一个简单的例子:
const obj1 = { name: "Object 1" }
const obj2 = obj1; // the same object, not copy
obj2.name = "Object 2"; // affecting the object referred by obj2, which _is_ the object referred by obj1
console.log(obj1.name);
如果它是一个原语(例如字符串、数字、布尔值),那么“单独变量”的行为就会像您期望的那样。
发布于 2022-06-27 12:35:19
这是因为您在HeroDetailsComponent中传递一个链接到选定的英雄对象。
[(ngModel)]="hero.name"语句可以像[ngModel]="hero.name"和(ngModelChange)="hero.name = $event"那样重新编写
当你在输入中编辑你的英雄名字时,ngModelChange会发出新的值并在你的英雄列表中变异英雄对象。
如果你想看你的英雄名单是如何变化的,你可以用这样的方式重写它:
export class HeroDetailsComponent implements OnInit {
@Input() hero?: Hero
constructor() { }
ngOnInit(): void {
}
onHeroNameChange(name: string): void {
this.hero.name = name;
}
}您的html将是:
<div *ngIf="hero">
<h2>{{hero.name | uppercase}} Details</h2>
<div>ID: {{hero.id}}</div>
<div>
<label for="hero-name">Hero name: </label>
<input id="hero-name" [value]="hero.name" (input)="onHeroNameChange($event.target.value)" placeholder="name">
</div>https://stackoverflow.com/questions/72771985
复制相似问题