Tips for deleting a certain element from an array with the aid of a service in Angular 9

Is there a way to remove an object named Test1 from an array of objects? I am struggling with finding the correct method to achieve this. If there are any errors in my code, please feel free to point them out. I have utilized a service to update the values in the array. You can take a look at my stackblitz for further insight. When the "Remove Name" button is clicked, I aim to eliminate the object with the name Test1 from the array. Any assistance in solving this issue would be greatly appreciated.

dashboard.component.html:

<button (click)="callFun('Test1')">Remove Name</button> 
 {{ deleteItemName }}
<app-optymodel></app-optymodel>

dashboard.component.ts:

callFun(name: any) {
    this.commonService.modifyDeleteItem(name);
    this.commonService.modifyNameList(name);
    this.commonService.modifyDeleteItem('');
  }

common.service.ts:

 modifyNameList(name: string) {
 const nameList = this.nameList.getValue();
 const result = nameList.filter((x) => x.name != name); 
 this.nameList.next(result);
 }

 modifyDeleteItem(name: string) {
 this.deletedItem.next(name); 
 }

After clicking the "Remove Name" button, the expected result is as follows:

const result = nameList.filter((x) => x != name); console.log(result);

[ 
{ name: 'Test2', id: '2' },
{ name: 'Test3', id: '3' },
{ name: 'Test4', id: '4' },
{ name: 'Test5', id: '5' },
];

Demo: https://stackblitz.com/edit/angular-pass-table-data-to-input-property-zn22go?file=src%2Fapp%2Fservices%2Fcommon.service.ts

Answer №1

Your stackblitz code actually differs from what you presented here. The following line:

const result = nameList.filter((x) => x != name); 

should be changed to:

const result = nameList.filter((x) => x.name !== name); 

This adjustment will prompt a lint warning or compile error due to the incorrect type declaration of your name list. You have specified it as Array<string>, while it should actually be

Array<{name: string, id: string}>
. It is advisable to use a type or an interface for the contents of the array.

Alternatively, instead of using Array.filter, you can utilize Array.splice if you only intend to remove one item (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice?retiredLocale=de#remove_1_element_at_index_3)

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

Confirm whether the Iterator type is the same as the AsyncIterator type

Is there a clever JavaScript technique to differentiate between Iterator and AsyncIterator without initiating the iteration process? I'm attempting to create a type checker like this: function isAsyncIterator<T>(i: Iterator<T> | AsyncIter ...

Exploring the mechanics behind optional chaining, known as the Elvis operator, in TypeScript. How does this feature operate within the

Can someone explain the concept of optional chaining (Elvis operator) in TypeScript and how it can be used effectively? public static getName(user: IUser){ if(user.firstName != null && user.firstName != ""){ return user.firstName; } ...

Storing various checkbox values into a database

I have a form with checkboxes that I need to submit to an API for database storage. This is the city.page.html <ion-item *ngFor="let city of cities;"> <ion-checkbox [(ngModel)]="city.id" ></ion-checkbox> <i ...

Is it possible to traverse through a series of variable names in TypeScript to access a child object?

I am attempting to update the following code: this.selectedArray1.indexOf(someIndexObject); Here is the code I want to use as a replacement: var someVariable = "selectedArray1" this[someVariable].indexOf(someIndexObject); However, when I make the repla ...

Encountering Blank PDF Files After Downloading in Angular

I am facing a challenge while attempting to download a PDF from an API. The data retrieval process seems to be smooth; here is an example of the retrieved content: https://i.sstatic.net/k6Yvy.png Within my Angular application, I am utilizing the ngx-file ...

Rxjs: accessing the most recent value emitted by an observable

As shown in the demo and indicated by the title const { combineLatest, interval, of } = rxjs; const { first, last, sample, take, withLatestFrom } = rxjs.operators; const numbers = interval(1000); const takeFourNumbers = numbers.pipe(take(4)); takeFourNu ...

The Extended Date type is indicating that the function cannot be located

I came across this helpful gist with date extensions: https://gist.github.com/weslleih/b6e7628416a052963349494747aed659 However, when attempting to use the functions, I encountered a runtime error stating: TypeError: x.isToday is not a function I foun ...

Creating a Persistent Top Navigation Bar using Bootstrap and Angular

I am struggling to implement a fixed top navbar in Angular. The structure of my main app.component template is as follows: <page-header></page-header> <router-outlet></router-outlet> The bootstrap navbar is included within my ...

Retrieve a particular item using the NGXS selector and incorporate it into the template

I am retrieving stored configuration settings from an API. Each setting includes an 'ID' and several properties like 'numberOfUsers', etc. I am utilizing NGXS for managing the state. My goal is to specifically fetch the 'numberOf ...

Concealing a VueJs component on specific pages

How can I hide certain components (AppBar & NavigationDrawer) on specific routes in my App.vue, such as /login? I tried including the following code in my NavigationDrawer.vue file, but it disables the component on all routes: <v-navigation-drawer ...

Creating your own custom operator using observables is a powerful way

const apiData = ajax('/api/data').pipe(map((res: any) => { if (!res.response) { console.log('Error occurred.'); throw new Error('Value expected!'); } return res.response; }), An enhancement is needed to encapsulate the ...

Angular 9: Issues with BehaviorSubject when fetching data from a remote source

I am currently facing an issue with passing data between components using BehaviorSubject. My code works perfectly fine for static data, but when it comes to remote data fetched from an API, the component that is supposed to receive the updated data ends u ...

A guide on parsing a stringified HTML and connecting it to the DOM along with its attributes using Angular

Looking for a solution: "<div style="text-align: center;"><b style="color: rgb(0, 0, 0); font-family: "Open Sans", Arial, sans-serif; text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing e ...

The TypeError occurs when attempting to access the 'modelReplicationStartDate' property of an undefined entity

Encountering an issue while running Angular unit tests with Jasmine/Karma, resulting in the error message below: TypeError: Cannot read property 'modelReplicationStartDate' of undefined error properties: Object({ longStack: 'TypeError: Canno ...

A custom function that changes the state of a nested object using a specified variable as the key argument

My goal is to update the state of an object using a function called updateDatas. This function takes the arguments key, possibly subKey, and value. interface Datas { code: number; item1: Item; } interface Item { id: number; name: string; } const ...

The 'MutableRefObject<null>' type is lacking the following properties that are present in the 'Element' type

I'm eager to implement intersection observer in my React Typescript project. (https://www.npmjs.com/package/react-intersection-observer) However, I encountered an issue with setting the root: const root = useRef(null); const { ref, inView, entry } ...

Typescript encountering issues with addEventListener

const [status, setStatus] = useState<string>("pending"); const updateStatus = (newStatus: string) => { setStatus(newStatus); }; useEffect(() => { window.addEventListener("updateProtocol", updateStatus); return () =&g ...

Steering clear of using relative paths in Angular CLI

I am currently using the most up-to-date Angular CLI and have set up a custom components folder to store all of my components. For instance, within the TextInputComponent, there is a TextInputConfiguration class located in src/components/configurations.ts ...

How come TypeScript doesn't throw an error when I pass the incorrect type as a function parameter?

<template> <div class="app"> Greetings, {{ name }} <button @click="updateName('Jane')">Modify Name</button> </div> </template> <script lang="ts"> import { define ...

Using Angular 4 to retrieve a dynamic array from Firebase

I have a dilemma while creating reviews for the products in my shop. I am facing an issue with the button and click event that is supposed to save the review on the database. Later, when I try to read those reviews and calculate the rating for the product, ...