Angular 8's array verification feature lacks the ability to recognize preexisting elements

I've been trying to add and delete items in an array when a user selects or deselects the same item. However, it appears that either my array is not working properly or there is a bug in my code causing it to fail.

<div class="grp-input">
                        <label class="input-title">Member Search</label>
                        <input type="text" (keyup)="onSearchMember()" [(ngModel)]="memberName" class="form-control field-font" placeholder="Enter Member Name">
                    </div>


<div class="members-div d-flex flex-row col-lg-6" *ngFor="let member of memberData">
                    <div class="member-checkbox">
                        <input class="checkbox checkmark" (change)="selectMember(member,$event)" type="checkbox" name="cb" id="cb1">
                    </div>
                    <div>
                        <img class="member-img" [src]="img" alt="">
                    </div>
</div>

typescript code

memberData: Array<any> = [];
selectedMembers: Array<any> = [];

selectMember(member, e) {
    if (e.target.checked) {
      if (this.selectedMembers.length == 0) {
        this.selectedMembers.push(member);
      }
      else if (this.selectedMembers.length > 0) {
        const index = this.selectedMembers.indexOf(member.email);
        if (index > -1) {
          this.selectedMembers.splice(index, 1);
        }
        else if(index==-1)
        {
          this.selectedMembers.push(member);
        }
      }
    }
    else {
      const index = this.selectedMembers.indexOf(member);
          this.selectedMembers.splice(index, 1);
    }
    console.log("selected members",this.selectedMembers);

  }

onSearchMember() {
    var param;
    if (this.memberName) {
      param = {
        "pageNo": 0,
        "pageSize": 6,
        "name": this.memberName
      };
    } else {
      param = {
        "pageNo": 0,
        "pageSize": 4,
        "name": ""
      };
    }

    this.quoteService.get(constants.searchMember, param).subscribe(result => {

      if (result != "") {
        console.log(result);
        this.memberData=result;
      }
      else {
        //swal.fire(result.status, result.msg, 'warning');
      }

    }, error => {
      swal.fire(error.status, 'Opps!Something went wrong.', 'warning');
    });
  }

I have encountered an issue where after searching for a member, clearing the search input field, and then selecting the same existing item again, the array treats it as a non-existing element and pushes it. It's quite frustrating. Can anyone provide some assistance with this problem? If more explanation is needed, please let me know.

Answer №1

When searching for a member's email within the selectedMembers array, using

const index = this.selectedMembers.indexOf(member.email);
will always result in -1 if the array contains the entire member object rather than just emails.

To address this issue, it is necessary to iterate through the selectedMembers array and check for a member with the same email:

const index = getMemberIndex(member.email);

getMemberIndex(email){
  for(let i=0;i<this.selectedMembers.length;i++){
      if(this.selectedMembers[i].email==email){
        return i;
      }
  }
  return -1;
}

Alternatively,

You can utilize lodash from https://www.npmjs.com/package/lodash to find the object index based on a property:

const index=_.findIndex(this.selectedMembers,{email:member.email});

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

Improving event observation efficiency with Observable.fromEvent on the browser window

Within my file manager UI, each individual file item is currently set to monitor the window's wheel event. As soon as a file item comes into view on the page, its corresponding image loading process will be initiated by the file item component. While ...

Struggling to properly test the functionality of my NgForm call in Angular2+

I've been trying to test the login functionality by inputting username and password in an NgForm, but I keep encountering unsuccessful attempts. Is there a vital step that I may be overlooking? Currently, I'm facing this error message: Chrome 6 ...

Switching between API requests through a live feed

Hey there: import Rx from 'rxjs'; function mockApi(endpoint, time, response) { return new Rx.Observable(observer => { console.log(`${endpoint}: Request initiated.`) let active = true; const id = setTimeout(() => { cons ...

Checking Whether a Value Entered in an Input Field Exists in an Array Using jQuery

Can someone help me with checking if a specific value is in my array? I want to achieve something like that, any suggestions on how to do it? if(jQuery.inArray($('#ValueInputTitle').val, variableValueInput) !== -1) { console.log("is in arr ...

Adjust the dimensions of the bootstrap dropdown to match the dimensions of its textbox

The second textbox features a bootstrap dropdown with extensive content that is overflowing and extending to other textboxes below it. I am looking for a way to resize the dropdown to fit the size of its corresponding textbox. UPDATE: I want the dropdown ...

I am experiencing an issue where my Visual Studio Code extension is failing to display code correctly

Hey everyone, I'm a student and a beginner in Visual Studio code. Recently, I was working with Java Script and ran into an issue. Every time I tried to save my code by pressing Ctrl+S, it would automatically indent the code, causing problems in my ter ...

Instructions on how to ensure that an AJAX call will only function when the user is logged in within a Rails application

My application allows users to save photos by clicking on them, but this feature is only available when the user is logged in. Strangely, even when a user is logged out, they can still click on a photo and save it because the show page is identical for bot ...

When working with React-Native App and combining React-Navigation with Redux, a common error may occur stating that 'action.routeName' is not an object. This issue can be

I encountered an error in my React Native app while implementing react-navigation within redux. The issue, along with a screenshot for reference, can be found here. Currently, I have not incorporated any redirects into the application. However, my plan in ...

Tips for avoiding the persistence of an old array on the screen after refreshing and showing the new, updated array

Currently, my task involves displaying array values on a webpage. The array data is sourced from a real-time database in Firebase. After adding new values to the array or inputting another value into the database on the previous page, we are redirected to ...

Error message from webpack: It appears you are missing a necessary loader to handle this specific file type

I'm struggling with building my server.ts typescript file for the backend. I have some imports, but my app is not building. Here is a snippet from my typescript file: import * as Express from 'express' import * as Session from 'expres ...

Ways to implement a placeholder height for images on a webpage with varying heights using HTML

I'm facing an issue with an image on my website that has a dynamic width and height as defined by the following CSS: .sm_item_image { width:100%; height:auto; max-width:400px; } The problem arises when the image takes some time to load, ...

What is the process for sending a parameter in getStaticProps within Next.js

Is there a way in NextJS to call an API when a user clicks the search button and display the relevant result? Thanks for your input! The API I'm currently utilizing is , with "Steak" referring to the specific food item of interest. In my development ...

Two-way data bindings trigger the digest() function to iterate 10 times

I'm facing issues with angular binding and my experience level in this area is limited. I will be posting all related questions here. I have a piece of angularjs code that is triggering 10 digest() cycle reached errors. After researching similar posts ...

Retrieve a specific key value from a dictionary within a Flask function by employing JavaScript

I'm currently working on a feature where a user can input something in a search field, and upon submitting, the script should send a request to a Flask function using JavaScript. The response data should then be loaded accordingly. However, I've ...

I keep receiving multiple header errors from ExpressJS even though I am positive that I am only sending a single header

Can someone please help with the issue I'm facing in the code below: router.put("/:_id", async (req: Request, res: Response) => { try { // Create the updated artist variable const artist: IArtist = req.body; const updatedArt ...

Easy jQuery Mobile and AJAX login solution

My current project involves creating a mobile app with user login capabilities using PhoneGap, jQuery Mobile, AJAX, and PHP. I am starting with a basic HTML and PHP structure as I am not an experienced programmer, but even my simple user login form is not ...

Safari is causing issues with HTML5 Video playback

I have a client with a media-heavy website containing numerous video and audio files. While the videos load perfectly on Chrome, Firefox, and IE, they do not load on Safari for Windows. Here's a snippet of the code: <video controls="controls" type ...

Navigating through different views in a Vue application using Vue Router directly from Vuex actions

Currently, I am in the process of developing a web application using Vue 2.x and Vuex 2.x. In this project, I need to retrieve some data from an external source via an http call. If this call fails, my objective is to redirect to a different page. GET_PET ...

Avoid navigating through hidden tab indexes

Below is the HTML code that I am working with: <span tabindex="19"> </span> <span tabindex="20"> </span> <span tabindex="21"> </span> <span id="hidden" tabindex="22"> </span> <span tabindex="23"&g ...

Delivering a Captivating JavaScript Pop-Up upon Page Loading

I have a simple pop up window (with no content) that triggers with the 'onclick' event. How can I modify the code below to make the popup appear automatically when the page loads? <head> <title>Popup Display</title> < ...