我使用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>发布于 2019-12-12 15:00:13
变异原始数组并从数组中返回删除的项,从MDN的语法可以看出:
var arrDeletedItems = array.splice(start[,deleteCount[,item1[,item2,.]])
因此,您应该直接看到posts中的变化。不要这样reassign:
this.posts = this.posts.splice(i, 1);只要这样做就行了:
this.posts.splice(i, 1);https://stackoverflow.com/questions/59307245
复制相似问题