私はAngular2について学んでいます& RxJS observables。私はシミュレートされたhttp.getとの結果を表示するシンプルなフォームを作成しました。は新しいアイテムを作成することができます。ngの内部での行動について<form>
新しいアイテムをngForで参照される配列の最上部に追加し、表示されたアイテムのリストの先頭に拡張機能を追加したいので、これを達成するためにpush()とは対照的にunshift()を使用しました。しかし、私がこのアプローチを使用するとき、私はいくつかの望ましくない動作を見ます。新しい項目が配列に追加されると、既存の出力の最初の項目が変更されます。
私が言ったように、私はちょうど学んでいるので、私は何かを見逃してしまった場合、plsは忍耐強いですが、誰かが私がここで何が起こっているのか理解するのを助けることができますか?私は私の問題を説明するためにこの塊を作りました。どんな洞察力も大変高く評価されます。
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'demo',
template: `
<button (click)="createItem()">Create</button>
<button (click)="getItems()">Reset</button>
<form>
<div class="form-group" *ngFor="let item of items; let i=index" >
<div style="padding-top: 50px;">
<div class="col-xs-4">
<label id="itemIdLabel-{{i}}" for="itemIdDiv-{{i}}">Id</label>
<div id="itemIdDiv-{{i}}">{{item.id}}</div>
</div>
<div class="col-xs-8">
<label id="itemNmLabel-{{i}}" for="itemNmInput-{{i}}">Name</label>
<input id="itemNmInput-{{i}}" name="itemNmInput-{{i}}" [(ngModel)]="item.nm" type="text" class="form-control">
</div>
<div class="row" style="padding-top: 10px;">
<div class="col-xs-12">
<button (click)="deleteItem(item.id, i)">Delete</button>
</div>
</div>
</div>
</div>
</form>
`,
})
export class DemoComponent implements OnInit{
items = new Array<Item>();
constructor() {}
ngOnInit(){
this.getItems();
}
getItems(){
this.initItems();
}
createItem(){
//create a new item without an id. this will be committed once required fields are filled
//this works fine
//this.items.push(new Item("new", "newItem"));
//this does not
this.items.unshift(new Item("new", "newItem"));
}
deleteItem(id, index){
this.items.splice(index,1);
}
initItems(){
//simulating data coming back from a web service call with ids intact
this.items.length = 0;
this.items.push(new Item("first", "firstItem"));
this.items[0].id = '001';
this.items.push(new Item("second", "secondItem"));
this.items[1].id = '002';
this.items.push(new Item("third", "thirdItem"));
this.items[2].id = '003';
}
}
export class Item {
public id: string;
constructor(public nm: string,
public dsc: string){}
}
*質問に[MCVE] *入れてください。 – jonrsharpe
あなたの要求に応じて – rswillis
** M **と** C ** **は 'Item'の詳細、' ItemService'、完全なHTMLマークアップはすべて関連していますか?どちらかを切り取ったり、それらを組み込んでください。 – jonrsharpe