Eliminate Elements from Array - Angular Four

I am currently developing a basic to-do app using Angular4. The setup of the app is structured as follows:

Form Component: Responsible for adding items to the to-do list
Item Component: Represents individual to-do items
App Component: Contains a *ngFor loop to display all the to-do items.

I have implemented a new button in the item component to delete the respective item. However, I am facing difficulty in determining the correct index number to splice or filter out the item.
You can access the GitHub repository here

Here are the code snippets:

<app-navbar></app-navbar>
<div class="container">
  <app-form (itemAdded)="onItemAdded($event)"></app-form>
  <div class="row">
    <div class="col-md-3 mb-3"
    *ngFor="let item of toDoList; let i=index">
      <app-item
      [listItem]="item"
      (itemDeleted)="onItemDeleted($event)"></app-item>
    </div>
  </div>
</div>

app.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  toDoList = [
    {
      name: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
    }
  ];

  onItemAdded(itemData: {itemName: string}){
    this.toDoList.push({
      name: itemData.itemName
    });
  }

  onItemDeleted(index: number){
    this.toDoList.splice(index, 1);
  }
}

form.component.html:

<div class="title">
  <h1 class="display-4">{{ title }}</h1>
</div>
<div class="input-group">
  <input type="text" class="form-control" [(ngModel)]="newItem">
  <span class="input-group-btn">
    <button class="btn btn-success" type="button" (click)="onAddItem()">
      <fa name="plus"></fa>
    </button>
  </span>
</div>

form.component.ts:

import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
  @Output() itemAdded = new EventEmitter<{itemName: string}>();
  title = 'To-Do List';
  newItem = '';

  constructor() { }

  ngOnInit() {
  }

  onAddItem(){
    this.itemAdded.emit({itemName: this.newItem});
  }

}

item.component.html:

<div class="task">
  <div class="mb-5 d-flex justify-content-between">
    <fa name="circle-o" size="3x"></fa>
    <button type="button" name="delete" class="btn btn-danger align-self-end" (click)="onDeleteItem()"><fa name="trash"></fa></button>
  </div>
  {{item.name}}
</div>

item.component.ts:

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-item',
  templateUrl: './item.component.html',
  styleUrls: ['./item.component.css']
})
export class ItemComponent implements OnInit {

  @Input('listItem') item: {name: string};
  @Output() itemDeleted = new EventEmitter<{index: number}>();

  constructor() { }

  ngOnInit() {
  }

  onDeleteItem() {
    this.itemDeleted.emit() //need help with this
  }
}

Answer №1

Here's a different approach:

<custom-component [data]="element" (deleted)="onDeleted(i)"></custom-component>

onDeleted(position) {
    this.dataArray.splice(position, 1);
}

Answer №2

If you want to remove an item from a list in JavaScript, you have a couple of options:

onDeleteItem(id: number) {
    this.list = this.list.filter(item => item.id !== id);
}

Alternatively, you can use .splice(). However, with this method, you will first need to find the index of the item in the array:

const index: number = functionToGetTheIndex();
this.list.splice(index, 1);

To retrieve the index, you can iterate through the list and compare IDs like so:

for(var i = 0; i < this.list.length; i++) {
   if(this.list[i].id === id) {
     return i;
   }
}

*Edit: "int" should be corrected to "number"

Answer №3

Here's a quick solution for removing items from your array without referencing the code.

myArray = myArray.filter(x => x.ITEM !== ITEM);

*Correction: typographical error fixed

Answer №4

Here is an example of how you can implement the code:

Firstly, make sure to declare rowItems at the beginning:

rowItems: RowItems = new RowItems(0, "", "", new Array<Something>());

Next, include the following method in your code:

deleteRowOfSomething(rowIndex: number) {
        console.log("removing row index: " + rowIndex);
        this.rowItems.splice(rowIndex, 1);
        this.changeDetectorRef.detectChanges();
    }

Remember to import the necessary libraries for changeDetectorRef.

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

Should the updater method be placed in the state or passed directly to the context?

Is it better to have this context setup like so: <MatchContext.Provider value={this.state.match}> Or should I structure it as follows in my state? match: { match: null, updateMatch: this.updateMatch }, Which approach is more eff ...

Create an array in JavaScript using the JSON data that was returned

After receiving some JSON data from a REST call, I have successfully parsed and added totals to the data. The results can be viewed on the page (refer to this post: json sibling data). However, now I want to further break down the totals. Here is the initi ...

Angular 6 - Resolving the Issue of 'Function calls are not supported in decorators' in Production Builds

Currently, I'm in the process of developing a cutting-edge Angular 6 application. However, as I was progressing with the development phase and tried to create a prod build using the following command: ng build --prod To my dismay, I encountered a pe ...

Ways to conduct testing on React Native Typescript app COMPONENTS using jest

I've been struggling to set up testing for my React Native Typescript Components using Jest. Despite searching through various examples and solutions (such as this one, that one, another link, etc.), I still can't seem to get it working. Even fol ...

Are you looking to load pictures using jQuery?

I am currently using a ul li menu setup as follows: <ul> <li><a href="#1">Image #1</a></li> <li><a href="#2">Image #2</a></li> <li><a href="#3">Image #3</a></li> ...

When I attempt to incorporate multiple sliders on a single page, I encounter difficulties in determining the accurate stopping position if the number of slides varies

I am having trouble setting the correct stop position for sliders with different numbers of slides on a page. When I have the same number of slides in each slider, everything works fine. However, I need to have a different number of slides in each slider ...

Using jQuery's toggle function with a double click event to change the display to none

A div I created has the ability to expand to full screen upon double click, and I now wish to implement a toggle function so it can return to its original size when double clicked again. Initially, the code successfully increased the size of the div. Howe ...

Tips for concealing query parameters that are empty or undefined in Angular 2

I'm currently working with Angular2 (RC2) and the new Router (Alpha.8). Is there a way to prevent a query parameter from being displayed in the URL if it is undefined? For example: this.router.navigate(["/results", this.month, this.day], { ...

Steps for including a new script in package.json

Is there a way to add the script dev to my package.json from the terminal? I attempted to manually add it using a text editor, but when I try to run: npm run dev I encounter some errors. Is there a way to include this script through the command line? E ...

Tips for concealing the top button on a mat calendar

I have a calendar for a month and year, but when I click on the top button it also displays the day. How can I hide that button or instruct the calendar not to show the days? Check out this image I was thinking of using a CSS class to hide that element. ...

Encountering issues with package resolution in VS Code while setting up a monorepo with yarn workspaces, Vite, React, and

I recently set up a monorepo using yarn@3 workspaces. Here is the structure of my root package.json: { "name": "hello-yarn-workspaces", "packageManager": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Can anyone assist me with this HTML/jQuery code?

Despite my efforts, I've been unable to achieve success. The challenge I'm facing is with duplicating controls for adding images. I have a button and a div where the user can choose an image by clicking the button. The selected image appears in ...

Extract the JSON information to find the <highlighting> tag used to emphasize text within a specific field

{ "responseHeader": { "status": 0, "QTime": 32 }, "response": { "numFound": 21, "start": 0, "docs": [ { "description": "A unique wave design sets apart this wedding band, craft ...

What is the most effective approach for preventing the inadvertent override of other bound functions on window.onresize?

As I delve deeper into JavaScript, I constantly find myself pondering various aspects of it. Take for instance the window.onresize event handler. If I were to use the following code: window.onresize = resize; function resize() { console.log("resize eve ...

Is it considered inefficient to import every single one of my web components using separate <script> tags?

Currently, I am in the process of developing a website with Express + EJS where server-side rendering is crucial. To achieve this, I am utilizing web components without shadow dom. Each page type (home, post, page) has its own EJS view. For instance, when ...

Getting the response data from an XMLHttpRequest - Full guide with screenshots

Currently, I am working with autocomplete jQueryUI and have this code snippet: .autocomplete({ source: function( request, response ) { var results = $.getJSON( url, { term: extractLast( request.term ) }, response ); console.log(results); ...

Exploring the capabilities of for loops when working with arrays

I am working on computing the roots and squares of prime numbers stored in an array. After some coding, I managed to store the results in two new arrays. Here is my solution: import java.util.Arrays; import java.lang.Math; public class Array1 { ...

What is the proper way to define the scope for invoking the Google People API using JavaScript?

I am attempting to display a list of directory people from my Google account. export class People { private auth: Auth.OAuth2Client; private initialized: boolean = false; private accessToken: string; constructor(private readonly clientEmail: strin ...

Error in Prisma: Unable to retrieve data due to undefined properties (attempting to access 'findMany')

Recently, I've been working on a dashboard app using Prisma, Next.js, and supabase. Encountering an issue with the EventChart model in schema.prisma, I decided to create a new model called EventAreaChart. However, after migrating and attempting to ex ...

Looking to switch up the hide/show toggle animation?

Currently, I have a functioning element with the following code. It involves an object named #obj1 that remains hidden upon page load but becomes visible when #obj2 is clicked. #obj1{ position:fixed; width:100px; bottom:180px; right:10 ...