Manipulating an array in Angular by popping elements based on the ongoing iteration of ngFor loop

Let me explain the issue I'm facing with my ngFor loop and component deletion functionality. Here is how I generate the component using ngFor:

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

In my TypeScript file, the 'cardDeletion' function looks like this:

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

The goal is to delete only the specific component that triggers the 'deleteCardEmit' event. Here is the button in the child component responsible for triggering component deletion:

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

This is the @Output emitter setup:

@Output() deleteCardEmit = new EventEmitter;

And here is the 'deleteCard' function implementation:

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

I initially tried passing the index from ngFor into the pop method as shown below but it didn't work:

this.cardElements.pop(i)

If you have any suggestions or solutions, please share them as I am relatively new to web development. Your help would be greatly appreciated!

Answer №1

My method for handling this situation involves emitting the element that needs to be deleted and then filtering the array to remove that specific element.

Here is an example:

  <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);
}

By implementing this process, you can effectively filter out the unwanted element and trigger a page refresh through digest stimulation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to retrieve information from service using Angular 1.6 and TypeScript

I'm having an issue retrieving data from a Service in my Controller. Here is the code for my Service file: import {IHttpService} from 'Angular'; export class MyService { public static $inject = ['$http']; constructor(private $htt ...

Managing asynchronous variable assignment in Angular: tips and tricks

Within my Angular 6 application, there is a service where I declare a variable named "permittedPefs". This variable is asynchronously set within an httpClient.get call. @Injectable() export class myService implements OnInit { permittedPefs = [] ...

Developing a structure or definition for a Map

Currently, I have created a type and interface in TypeScript to explicitly define the things variable and the Map constructor call. type Things = Map<string, ThingValue>; interface ThingValue { label: string; count: number; } const things: Thi ...

Challenges faced with the Nativescript Software Development Kit

I am currently working on a Nativescript app with Angular and using a JSON server. However, I am facing some errors when I try to run 'tns run android' or 'tns doctor' commands. × The ANDROID_HOME environment variable is either not se ...

Can someone please explain the process of including options in a dropdown menu using Angular 2?

In my dropdown menu, I have the months of the year translated using a pipe syntax like this: {{'January' | translate}} I am looking to bind these translated months in my dropdown. Below is the HTML and the object containing the months: <sele ...

The pivotal Angular universal service

In my application, I have the need to store global variables that are specific to each user. To achieve this, I created a Service that allows access to these variables from any component. However, I am wondering if there is a way to share this service t ...

Struggling to configure setupProxy.js with Duende ASP.NET Core BFF in a TypeScript React project - any tips?

I'm facing some challenges with getting the proxying to work for my local development setup of a Duende BFF with ASP.NET Core 6 and a TypeScript version of a create react app. To check out the repository I've been working on, visit: https://gith ...

How can I achieve the same functionality as C# LINQ's GroupBy in Typescript?

Currently, I am working with Angular using Typescript. My situation involves having an array of objects with multiple properties which have been grouped in the server-side code and a duplicate property has been set. The challenge arises when the user updat ...

Assign a class to an Angular component's host element without any conditions

In my Angular project, I have a component where I need to apply a class unconditionally. To achieve this, the host property within the @Component decorator can be used: import { Component } from '@angular/core'; @Component({ selector: 'ap ...

What is the best way to bypass using an if/else statement in TypeScript when dealing with mocha and returning undefined values

A unique spline able to be intertwined and produce a new version of itself, most of the time. export default class UniqueSpline { public intertwinedCount: number; constructor(parent?: UniqueSpline) { this.intertwinedCount = parent && pare ...

Is it possible for Typescript to utilize Webpack's UMD feature for importing

Is there a method in TypeScript to import a module wrapped by webpack UMD (Universal Module Definition)? For instance: npm install knockback The file .js (node_modules/knockback/knockback.js) starts like this: (function webpackUniversalModuleDefinition( ...

Updating Angular from version 9 to 11 causes issues with router.navigate not being able to properly load a new component

After updating my Angular project from version 9 to 11 (with an upgrade to version 10 in between), I encountered a strange routing issue. In version 9, the method below worked perfectly fine. However, in version 11, although the URL changed to 'upload ...

When using NestJS and Serverless, the error message "handler 'handler' is not a function" may be encountered

Currently, I am in the process of incorporating NestJS as an AWS Serverless function using serverless-framework. Following the official documentation, my code mirrors that of the documentation. However, upon launching it, I encounter the error message Fai ...

Can you suggest a way to revise this in order to include the type of property (string)?

Here is a snippet of working code that raises a question about refactoring to improve the readability and functionality. Consider renaming the method to isPropValueSame. import * as _ from 'lodash'; const diff = _.differenceWith(sourceList, comp ...

What could be causing axios to not function properly when used with async/await in this particular scenario

I need to update the DoorState when a button is clicked. After sending a request to the API to change the DoorState, I then call another API to check the status of the robot. Even though the DoorState has been successfully changed, it seems that the chan ...

Is there a way to set a custom port number for an Angular application?

I am currently in the process of constructing an Angular application. The application is designed to communicate with a server via HttpClient. However, each time the application connects to the server, it utilizes a different port. I am interested in confi ...

Utilizing a TypeScript getter or local variable to reference a service variable within an Angular component

Suppose you have an array of objects stored in a service export class DataService { private _dataSources : Array<DataSource> contructor(private callerService: CallerService){ this._dataSources = this.callerService.getDataSources(); // fetc ...

When I click on the button, the output does not appear

Even though I know how to write this in pure javascript, I am new to angular so when I click submit, nothing happens and I don't get any result. index.html <input type="text" ng-model="username" placeholder="Username"> <input type=" ...

Sorting through a JavaScript array

I am facing a peculiar problem while trying to filter an array in TypeScript. Here is the structure of my object: Sigma.model.ts export class Sigma { sigmaId: number; name: string; userId: number; starId: string; } `` The starId property contains com ...

The RxJs Observer connected to a websocket only triggers for a single subscriber

Currently, I am encapsulating a websocket within an RxJS observable in the following manner: this.wsObserver = Observable.create(observer=>{ this.websocket.onmessage = (evt) => { console.info("ws.onmessage: " + evt); ...