【问题标题】:How do I display an index change in ngFor (Angular)如何在 ngFor (Angular) 中显示索引更改
【发布时间】: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


【解决方案1】:

如果您需要删除数组的n-th 元素,您可以像这样使用splice

  removePopUp(index) {
    index = Number(index);

    // check if provided index is number
    if (isNaN(index)) {
      return;
    }

    // check if provided index is within array length
    if (index < 0 || this.userPopUpsArray.length <= index) {
      return;
    }

    this.userPopUpsArray.splice(index, 1);
  }

注意:最好检查提供的索引是否为数字,以及它的值是否在数组长度内。请记住,为 splice 提供负值将从数组末尾开始查找,因此两项检查都是必要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-08
    • 2020-07-06
    • 2018-02-22
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 2017-11-24
    相关资源
    最近更新 更多