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

Honing into Angular 2 Events

I am struggling with something that should be simple, but I can't seem to make it work. My goal is to utilize screenfull, which is included in a theme I'm using, to enable fullscreen mode on the browser. Specifically, I want to execute certain ac ...

Modifying background with JavaScript and AJAX技术

I currently have a table structured like the following; <table style="width: 100%; border: solid 1px #666600; min-width: 800px" cellpadding="0" cellspacing="0"> <tr> <td id="aaa">&nbsp;</td> ... Using jQuery's ajax functi ...

Updating a hyperlink with data dynamically upon clicking a different button using jQuery

I need to create a script that will add the id of 'peter' to the hyperlink of anchor 'jack' when 'peter' is clicked. <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery. ...

requirements for navigating within an Angular application

Initially, if the first user is already logged in on the first tab and is redirected to the dashboard, when that same user opens a second tab in the same browser (by pasting the login URL), they are automatically redirected to the dashboard without having ...

Tips for wrapping a function call that may occasionally involve asynchronous behavior to ensure it runs synchronously

I am dealing with a function that functions as follows: _setDataChunk: function (action) { var self = this; /* some code */ var data = self._getDataChunk(action); populateWidget(data); } Sometimes GetDataChunk cont ...

Steps to reset default behavior after using event.preventDefault()

I came across a similar question on this post, but the solution provided did not work for my specific needs. So, I decided to share some example code and provide a bit of explanation... $(document).keypress( function (event) { // Pressing Up o ...

Align component within material-ui grid

Looking to center align the same cards but not just the grid component, I need the content itself to be equally distant from the borders and each other. I've searched and tried different solutions without luck. https://i.stack.imgur.com/aZj7H.png htt ...

Is there a JavaScript method for opening a new window regardless of the PHP file being used?

I have encountered a small dilemma that is causing me frustration. Currently, I have set up a BUTTON on my website. This button, when clicked, triggers a JavaScript function to open a "New Window". The code for this button and function looks like this : ...

The outcome of the JQuery function did not meet the anticipated result

Here is the code I am using: $("p").css("background-color", "yellow"); alert( $("p").css("background-color")); The alert is showing undefined instead of the expected color value. I have tested this code on both Google Chrome and Firefox. Strangely, it w ...

Adding a div to the preceding div based on matching IDs in AngularJS

Here is a representation of my layout in HTML: <div ng-repeat="message in messages"> <div ng-class="{'messages messages--sent': userId == message.id, 'messages messages--received': userId != me ...

"Encountering a Dojo error where the store is either null or not recognized

I encountered an issue with the function I have defined for the menu item "delete" when right-clicking on any folder in the tree hierarchy to delete a folder. Upon clicking, I received the error message "Store is null or not an object error in dojo" Can s ...

What could be causing the issue with my css `content:` not functioning across different browsers, and how can I enhance cross-browser compatibility in all cases

Working on my first HTML/CSS project, I encountered a browser compatibility challenge. The code functions well in Firefox, IE, and Edge but fails in Chrome. Specifically, I am trying to make a button display alternating up and down arrows when clicked. Whi ...

Using Vuex to calculate the percentage of values within an array of objects and dynamically updating this value in a component

I'm currently in the process of developing a voting application with Vuex. Within the app, there are buttons for each dog that users can vote for. I have successfully implemented functionality to update the vote count by clicking on the buttons: sto ...

Guide on injecting javascript code containing php variables into a php page

I have successfully developed a PHP page and Javascript code that includes some PHP variables. The code is designed to insert PHP variables into the database using Javascript: <?php $id = "Kevin"; $user = "Calvin"; ?> <!-- include jquer ...

Can you explain the significance of npm WARN excluding symbolic link?

Could you please explain the meaning of npm WARN excluding symbolic link? Also, any advice on how to resolve this issue? ...

Troubleshooting JavaScript directly on the client side

As a JavaScript beginner hoping to transform into a JavaScript expert, debugging is an essential skill I must master. Currently, I am utilizing Chrome debugger tools to tackle a complex array of spaghetti JavaScript code that resembles a cryptic puzzle wai ...

Encountered an error while running the `npx-create-react-app my-app` command in

When attempting to run 'npx create-react-app my-app', the following error message is displayed: 'npx' is not recognized as the name of a cmdlet, function, script file, or operable program. Double check the spelling and path included to ...

When I attempt to press the shift + tab keys together, Shiftkey is activated

Shiftkey occurs when attempting to press the shift + tab keys simultaneously $("#buttonZZ").on("keydown",function (eve) { if (eve.keyCode == 9 && eve.shiftKey) { eve.preventDefault(); $("#cancelbtn").focus(); } if (eve. ...

Get ready for 10 AM with the RxJS timer function

I am trying to figure out how to schedule a method in my code using rxjs/timer. Specifically, I want the method to run at precisely 10 AM after an initial delay of 1 minute. However, my current implementation is running every 2 minutes after a 1-minute d ...

JS: Initiating a new keypress operation

When I press the Tab key, I want it to do something different instead of its default action. Specifically, I have a text box selected and I would like it to add spaces (essentially making the textarea behave like a text editor). How can I trigger this type ...