【发布时间】:2022-01-01 18:21:20
【问题描述】:
我有一个名为 removePopUp 的函数。当我发送索引时,有时我想更改数组中该索引内的内容。假设我有一个 [0,1,2] 数组。当我运行 removePopUp(1) 应该返回 [0,2] 应该没有第 3 个元素,但第 3 个索引会滑动到删除该元素的第二个元素。问题是当我使用 ngFor 显示子组件时,它没有在 angularJs 中显示此活动。
messages.component.ts
...
userPopUpsArray : BookFaceMessage[] = []
...
removePopUp(index){
index = Number(index)
let usersLength = this.userPopUpsArray.length
if (usersLength === 3){
if (index === 1){
let thrid_index = this.userPopUpsArray[2]
this.userPopUpsArray[1] = thrid_index
}
else if(index === 0){
let second_index = this.userPopUpsArray[1]
let thrid_index = this.userPopUpsArray[2]
this.userPopUpsArray[0] = second_index
this.userPopUpsArray[1] = thrid_index
this.userPopUpsArray.pop()
}
else{
console.log(index)
this.userPopUpsArray.pop()
console.log(this.userPopUpsArray)
}
}
else if (usersLength === 2){
if(index === 0){
this.userPopUpsArray[0] = this.userPopUpsArray[1]
this.userPopUpsArray.pop()
}
else{
console.log(index)
this.userPopUpsArray.pop()
console.log(this.userPopUpsArray)
}
}
else{
this.userPopUpsArray.pop()
}
getPopUp(){
return this.userPopUpsArray
}
}
messages.component.html
...
<div *ngFor="let userPopUpData of userPopUpsArray; let i = index;trackBy: getPopUp">
<app-message-popup [userPopUpsArray]=userPopUpsArray [userPopUpData]=userPopUpData [removePopUp]=removePopUp [index]=i></app-message-popup>
...
</div>
【问题讨论】:
-
首先,我建议只使用 array.splice 来删除元素 - 就像
this.userPopUpsArray.splice(index,1)- 这将删除给定索引上的元素。关于更新视图 - 您使用的是哪种更改检测策略? -
您也可以尝试从模板中删除 trackBy,因为它不会在此表单中为您带来任何好处,并且可能会导致问题。
标签: javascript angular immutability ngfor