我有一个Angular组件,它有一个按钮,它将一个新对象添加到作为模型的数组中。在我的组件模板中,我有一个* ngFor循环,遍历数组中的对象并显示对象属性的输入字段。我还在每个从数组中删除对象的对象旁边都有一个“删除”按钮。当我执行以下步骤时,UI将与模型不同步并清空除第一个项目之外的所有项目的字段。角度模型和渲染不同步
- 通过单击“添加”按钮
- 填充了一些数据输入字段添加到阵列3个的新对象
- 点击中间的项目删除按钮来删除它
- 新增1通过点击“添加”按钮的对象
什么使UI与模型不同步?
这是一个Plunker示例,演示了问题Example 我还在模板中添加了一行显示模型数组中的内容。
@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;
}
如果有3个对象,当您填写自己的输入字段与一些随机字符串,去掉中间的一个,然后单击添加按钮再次它清除了一切 –
这是一个很好的问题 :)。要解决这个问题,只需将表单放入* ngFor – Cristophs0n