In the below the screen shot , mentioned nested element as child array.
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
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 usesplice()
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:
Note: This is based on the minimum facts provided. Appreciate it if you could provide the actual
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 arrayAnd