如何从列表框中删除元素 (PrimeNg)

How to remove an Element from a listbox (PrimeNg)

我有一个列表框,我想用它来添加和删除元素。

这是我的代码:

 <p-listbox #myListbox
           [options]="myListboxValues"
           [(ngModel)]="selectedValue"
></p-listbox>

myListboxValues 来自 SelectItem[] 类型。 我将列表的默认值作为对象数组获取。我遍历对象数组并将它们添加到 myListBoxValues。

public initListBox(objectArray:MyObject[]): void {
    this.myListboxValues = [];
    
    objectArray.forEach(currentObject =>{
      this.myListboxValues.push({label: currentObject.label, value: currentObject});
    });
}

添加函数:

public addToList(objectToAdd: MyObject): void{
  this.myListboxValues.push({label: objectToAdd.label, value: objectToAdd});
}

删除函数:

public remove(objectToRemove: MyObject): void{
    for (let _i = 0; _i < this.myListboxValues.length; _i++) {
       if(this.myListboxValues[_i].label === objectToRemove.label) {
          this.myListboxValues.splice(_i, 1);
       }              
    }
}

我的问题是,如果我调用删除函数,列表框不会刷新。 我必须单击它才能自行刷新。

编辑:我对 initListBox 函数有同样的问题。我必须单击列表框才能看到元素。

我建议您在示例数组中对引用类型数据所做的任何更改,始终使用先前值的副本进行操作,并将新对象分配给该变量。

所以不要做你在 addToList 中做的事情,而是尝试这样的事情,也为 remove:

public addToList(objectToAdd: MyObject): void{
  const newValue = {...this.myListboxValues}
  newValue.push({label: objectToAdd.label, value: objectToAdd});
  this.myListboxValues = newValue;
}

通过这种方式,您可以确保在对象引用更改时重新渲染。 你只是帮助你的渲染机器。

以您的方式进行本身并不错,但变异对象始终是每个框架检测的挑战。

我认为是因为Angular没有看到myListboxValues被修改了。也许你应该尝试另一种方式:

const myOtherListboxValues = this.myListboxValues;
for (let _i = 0; _i < myOtherListboxValues .length; _i++) {
   if(myOtherListboxValues [_i].label === objectToRemove.label) {
      myOtherListboxValues.splice(_i, 1);
   }              
}

this.myListboxValues = myOtherListboxValues;