skip to Main Content

In the below the screen shot , mentioned nested element as child array.

enter image description here

I wanted to remove child array element , I used below the script but it’s only remove first element.

removeChildWidget(parIndex:number,index:number){
    if (parIndex >= 0) {
       const widgetNumber = this.dashRightWidget[parIndex]?.widgetNumber;
       const widgeDashtNumber = this.dashboardWidgets[parIndex]?.widgetNumber;

       this.widgets.forEach((widget) => {
        if (widget.widgetNumber == widgeDashtNumber) {

          console.log("wid",widget.child[index])
          if (index >= 0) widget.child.splice(index, 1)
         console.log("wid",widget)
        }
      });
      console.log('final output', this.dashboardWidgets)
  
    }    
  }

2

Answers


  1. The problem is in the forEach loop. When you are iterating through the widgets array and check condition (widget.widgetNumber == widgeDashtNumber) it only matches one widget and when you use splice() it is called based on the first matching element. This results in only the first match being modified.

    To remove all child array elements you need to iterate over all items in the this.widgets array check each parent and remove the child if the condition is met.

    Refer the code below for more reference:

    removeChildWidget(parIndex: number, index: number) {
      if (parIndex >= 0) {
        const widgeDashtNumber = this.dashboardWidgets[parIndex] ? .widgetNumber;
    
        this.widgets.forEach((widget) => {
          if (widget.widgetNumber === widgeDashtNumber && widget.child && index >= 0) {
            widget.child.splice(index, 1); // Remove all children at the specified index if the widget.child exists
          }
        });
    
        console.log('Updated widgets:', this.widgets);
        console.log('Final output:', this.dashboardWidgets);
      }
    }

    Note: This is based on the minimum facts provided. Appreciate it if you could provide the actual

    Login or Signup to reply.
  2. In general you should avoid remove elements using javaScript. Make it in .html

    Really I don’t know about your code, but if you have a @for iterate over an array and only you need change the array

    @for (element in filteredArray;track $index)
    {
        @for (child in filteredArray.childs;track $index)
        {
            <your-child>
        }
    }
    

    And

    removeChildWidget(parIndex,index)
    {
         filteredArray[parIndex].child.splice(index,1);
         filteredArray[parIndex].child=[...filteredArray[parIndex].child]
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search