The list filter may not work properly if the search string is left blank

I am currently working on a list filtering feature that updates based on user input. As the user types, the system compares the entered text against the items in the list and displays the matching objects in an array. However, I'm facing an issue - when the search field is empty, the original, unfiltered list should be shown instead of the last successful search result.

HTML

<input type="text" class="in-line filter" id="searchByName" placeholder="Enter a name" (keyup)="filterByName($event.target.value)" />
<study-results-table [originalArray]="originalArray"></study-results-table>

TS

ngOnInit(){
  originalArray = new Array<any>();
  unfiltered = new Array<any>()
}

filterByName(searchString){
    this.filtered = new Array<any>();           
    _.each(this.originalArray, (result) => {
        let name = result.firstName.toLowerCase() +" " +result.lastName.toLowerCase();
        if(patientName.includes(searchString.toLowerCase())){
            this.filtered.push(result);
        }
    })

    if(searchString === ""){
        this.originalArray= this.unfiltered;
    }
    this.originalArray= this.filtered;
}

Can anyone provide guidance on resolving this issue?

Answer №1

Have you thought about utilizing the array's filter function in this scenario? You could streamline your code by implementing the following:

filterByName(searchString){
    if(searchString.trim().length==0){
        this.originalArray = this.unfiltered;
        return;
    };
    this.originalArray = this.unfiltered.filter( (result)=>{
        let fullName = result.firstName.toLowerCase() +" " +result.lastName.toLowerCase();
        return (fullName.includes(searchString.toLowerCase()));
    });
}

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

Using TypeScript to call a class method from within another function

Currently, I am working on an Angular 2 application and struggling to grasp the concept of TypeScript's this scope. Within my TypeScript class named SharedService, there is a function called handleError. If this function encounters a 401 status, I wa ...

Using PHP to send post requests with Ajax for DataTables functionality

I'm currently working on populating a datatable using datatables.net. There's a specific field that triggers an AJAX post request after it's changed. Here is the JavaScript code: jQuery(document).ready(function() { if(window.location.h ...

Value in any array matches

I need help finding a match array within an input value: var values = new Array('stackoverflow', 'google', 'yahoo'); var userInput = $('#txtAddress').val(); if ($.inArray(userInput, values) != -1) { alert(&apos ...

Guide to conducting Protractor testing with md-option

Working on an Angular project with the following code: <md-input-container> <label>Country </label> <md-select name="country" ng-model="country"required > <md-optgroup label="Select Country"> <md-option ng ...

Updating data in AngularJS after inserting a new record

What is the most efficient method to update comments data when a new record is added to the database? I currently have this code that works well, but I am concerned that it may be slow if there are a large number of comments. Any assistance would be greatl ...

"Exploring the World of Angular and Vue: Harnessing the Power

As a beginner developer, I've been busy familiarizing myself with Angular, React, and Vue. It seems like each of these frameworks use "declarative binding" and "templating". While I grasp the concept of what these are, I'm struggling to see why t ...

In Next.js, the Typescript compiler does not halt when an error occurs

I am looking to incorporate Next.js with TypeScript into my project. I followed the official method of adding TypeScript to Next.js using npx create-next-app --typescript. Everything seemed fine, but when a TypeScript error occurs (e.g. const st: string = ...

Setting up popover functionality in TypeScript with Bootstrap 4

Seeking assistance with initializing popovers using TypeScript. I am attempting to initialize each element with the data-toggle="popover" attribute found on the page using querySelectorAll(). Here is an example of what I have tried so far: export class P ...

Utilizing AngularJS to compare dates and select the next value from an array

I have a file containing holiday information in json format. I want to compare the current date with the list and show the next upcoming holiday. Can someone guide me on how to achieve the following? Format today's date for comparison with the holi ...

Ways to guarantee that the factory promise is fulfilled prior to the execution of the

So far, I have always found valuable help by studying existing answers on stackoverflow, but now I've hit a roadblock. I'm currently working on an app that utilizes a directive to generate calendar month boxes. <app2directive class="column_5 ...

Using AngularJS to apply conditional ngStyle

Can I achieve a similar effect to this using the following code: <span data-ng-style="vm.myFlag ? 'background-color:{{myObject.color}};padding:2px;border-radius:2px;' : ''"> The if-else statement in the above code does not work ...

Manipulating Data in AG-GRID with AngularJS: A Guide to External Editing

Currently, I'm in the process of developing a single-page application that utilizes AngularJS, UI-Router, and AG-GRID. However, I've encountered an issue with updating AG-GRID's data from an external form. Here is a breakdown of the problem ...

Guide on merging arrays and displaying them in a single table

After decoding three JSON arrays into PHP associative arrays, I am faced with the result shown in the following image: My next goal is to display these three arrays in a single table similar to the one depicted below: If you have any insights or suggesti ...

"Exploring the world of server-side and client-side MVC frameworks

I recently embarked on learning ASP.Net MVC and have encountered some puzzling questions regarding the MVC framework - particularly, whether it leans more towards client-side or server-side operation. I understand if these queries seem basic, but I'd ...

Why can't the file upload button locate its CSS styles?

Check out this jFiddle demonstrating the issue. Some of the Angular code may appear broken in the example, but that's just due to it being pasted into jFiddle; it's not an actual problem I'm facing. The CSS styles aren't working on the ...

Incorporating Angular module into the mean.io bundle

Need help with adding the angular-ui-grid module to a mean.io package: $ cd packages/custom/mypackage $ npm install angular-ui-grid --save To import the JS, add this line to packages/custom/mypackage/public/index.js: import 'angular-ui-grid'; ...

Angular 4 Web Application with Node-Red for Sending HTTP GET Requests

I am creating a unique service that utilizes Node-red to send emails only when a GET request is made to 127.0.0.1:1880/hello (node-red port), and an Angular 4 web app (127.0.0.1:3000) for client access. Upon accessing the /hello page from a browser, I rec ...

When attempting to integrate Angular 1.4's new router with components, an issue arises where a warning is triggered stating, "Failed to instantiate controller HeadlinesController

Attempting to work with Angular for the first time and struggling to load a component using data from an http request. Currently encountering a warning when attempting to execute the code with the HTTP request. Receiving a "Could not instantiate control ...

Validating forms using TypeScript in a Vue.js application with the Vuetify

Currently, I am attempting to utilize Vue.js in conjunction with TypeScript. My goal is to create a basic form with some validation but I keep encountering errors within Visual Studio Code. The initial errors stem from my validate function: validate(): v ...

Prevent ESLint from linting files with non-standard extensions

My .estintrc.yaml: parser: "@typescript-eslint/parser" parserOptions: sourceType: module project: tsconfig.json tsconfigRootDir: ./ env: es6: true browser: true node: true mocha: true plugins: - "@typescript-eslint" D ...