[英]Angular model and rendering out of sync
我有一个 Angular 组件,它有一个按钮,可以将新对象添加到用作模型的数组中。 在我的组件模板中,我有一个 *ngFor 循环,它遍历数组中的对象并显示对象属性的输入字段。 我在每个对象旁边还有一个“删除”按钮,用于从数组中删除该对象。 当我执行以下步骤时,UI 与模型不同步并清空除第一个项目之外的所有项目的字段。
是什么导致 UI 与模型不同步?
这是一个演示问题的 Plunker 示例示例我还在模板中添加了一行,显示模型数组中的内容。
@Component({
selector: 'my-app',
template: `
<div>
<button (click)="things.push({})">+ Add new thing</button>
<br />
<br />
<form #contactForm="ngForm">
<ng-container *ngFor="let thing of things;let i = index">
<input [(ngModel)]="thing.name" name="name-{{i}}" id="name-{{i}}" placeholder="name"/>
<br />
<input [(ngModel)]="thing.otherstuff" name="other-{{i}}" id="other-{{i}}" placeholder="other" />
<button (click)="things.splice(i, 1)">Remove</button>
<br />
<br />
</ng-container>
</form>
{{things | json}}
</div>
`,
})
export class App {
things: Awesome[]
constructor(){
this.things = new Array();
}
}
@NgModule({
imports: [
BrowserModule,
FormsModule
],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {
}
export class Awesome{
name?: string;
otherstuff?: string;
}
不要使用索引i为name属性提供值。 从数组中拼接项目时i不稳定,因此您必须为每个新添加的东西生成一个唯一的 id(我提供了一个生成唯一 id 的示例函数)。
下面的代码有效:
//our root app component
import { Component, NgModule, VERSION } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { FormsModule } from "@angular/forms";
@Component({
selector: 'my-app',
template: `
<div>
<button (click)="addEmptyItem()">+ Add new thing</button>
<br />
<br />
<form>
<ng-container *ngFor="let thing of things">
<input [(ngModel)]="thing.name" name="name-{{thing.id}}" id="name-{{thing.id}}" placeholder="name"/>
<br />
<input [(ngModel)]="thing.otherstuff" name="other-{{thing.id}}" id="other-{{thing.id}}" placeholder="other" />
<button (click)="removeItem(thing)">Remove</button>
<br />
<br />
</ng-container>
</form>
{{things | json}}
</div>
`,
})
export class App {
things: Awesome[]
constructor() {
this.things = new Array();
}
removeItem(thing): void {
this.things = this.things.filter(th => th.name !== thing.name);
}
addEmptyItem(): void {
let newItem = new Awesome();
newItem.id = this.guid();
this.things.push(newItem);
}
private guid() {
let uniqueId = Math.random().toString(36).substring(2)
+ (new Date()).getTime().toString(36);
return uniqueId;
}
}
@NgModule({
imports: [
BrowserModule,
FormsModule
],
declarations: [App],
bootstrap: [App]
})
export class AppModule {
}
export class Awesome {
id?: string;
name?: string;
otherstuff?: string;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.