我正在使用ngFor let let i = index;
,然后将i传递给接头,该接头将删除所有json元素,但会删除一个。代码的watchingGroup部分可以很好地进行拼接。仅仅是this.posts无法正常工作。
<div class="row" *ngFor="let post of posts;let i = index;">
点击按钮执行功能时,运行
this.posts = this.posts.splice(i, 1);
为什么不从i
中删除指定的元素?
removeFromWatchList(id: string, watchingGroup: string[], i) {
var index = watchingGroup.indexOf(this.userId); // <-- Not supported in <IE9
if (index !== -1) {
watchingGroup.splice(index, 1);
}
console.log(watchingGroup);
var unique = watchingGroup.filter(function(elem, index, self) {
return index === self.indexOf(elem);
});
this.uniqueResult = unique;
this.watchListService
.addToWatchList(auctionId, this.uniqueResult)
.subscribe(
res => {
this.counter++;
console.log("COUTNER: " + this.counter);
console.log("SUCCESS");
},
err => {
// Handle error response
console.log("ERROR");
}
);
this.posts = this.posts.splice(i, 1);
}
<div class="row" *ngFor="let post of posts;let i = index;">
<div class="col-md-9 col-centered">
<div class="listingCard" [@simpleFadeAnimation]="'in'" >
<div class=container>
<div class="row"> </div>
<div class="row">
<div class="col-md-5">
<button id="watchListButton" type="button" mat-raised-button (click)="removeFromWatchList(post.id, post.watchingGroup, i)"
[ngStyle]="{ 'background-color': (this.watchListItems ? 'green' : 'white'),'background-color': (!this.watchListItems ? 'white' : 'white') }">{{watchButtonValue}}</button>
</div>
</div>
答案 0 :(得分:2)
splice
对原始数组进行变异,并从该数组中返回已删除的项目,如MDN的语法所示:
var arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
因此,您应该直接在posts
中看到更改。不要reassign
这样:
this.posts = this.posts.splice(i, 1);
只需执行此操作即可
this.posts.splice(i, 1);