Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading