我有一個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