Home > Mobile >  Angular: Trying to pop an array based on current iteration of ngFor
Angular: Trying to pop an array based on current iteration of ngFor

Time:06-16

So I have a ngFor loop that generates a component I built as below;

<app-body *ngFor = 'let card of cardElements; index as i' (deleteCardEmit) = 'cardDeletion()' [currentCard] = 'card'></app-body>

In my TS file the function 'cardDeletion' does the following;

cardDeletion(){
    this.cardElements.pop()
  }

I basically want the pop to only delete the component the 'deleteCardEmit' originates from. Anything I place in the 'cardDeletion' function will work from the code below;

Button in the child component:

<button (click) = 'deleteCard()' > Delete job </button>

The @Output emitter:

@Output() deleteCardEmit = new EventEmitter;

The 'deleteCard' function:

deleteCard(){
    this.deleteCardEmit.emit();
  }

Apologies if my question does not make sense I've only been doing Web development for a week at this point with little prior programming experience. I had originally thought I could pass the index I get from my ngFor into the pop as so:

this.cardElements.pop(i)

But no luck - any help is appreciated.

CodePudding user response:

I would approach it in this way: emit the element to delete, filter the actual array with the element to be removed from it.

So:

  <app-body *ngFor = 'let card of cardElements; index as i' (deleteCardEmit) = 'cardDeletion(card)' [currentCard] = 'card'></app-body>
public cardDeletion(card) {
  this.cardElements = this.cardElements.filter(currentCard => card !== currentCard);
}

In this way you are filtering the element and stimolate the digest to refresh the page

  • Related