Steps to retrieve the search box input value and submit it in an AngularJs component using the Enter key

I'm facing an issue where I am trying to fetch the search list using speciesName from a table. However, when I attempt to retrieve the data by pressing the enter key, it is returning an error stating that the input data is undefined.

Is there a way to pass the search value to the TypeScript method within the same input field?

The TypeScript component code looks like this:

getSearchResult(speciesName) {

this.speciesName = speciesName;
this.speciesService.getSearchResult(speciesName).subscribe(result => {
  this.speciesList = result.results;
}, error => this.toastr.error(error.statusText, '', {
  timeOut: 3000
}));

}

The HTML for the component is as follows:

 <form class="form-inline" id="searchForm">
            <div class="form-group">
                <input class="form-control mr-sm-2" type="search" placeholder="Enter Species Name ..."
                    id="speciesNameSearch" name="speciesNameSearch" aria-label="Search"
                    (keyup.enter)="getSearchResult(speciesNameSearch)">
            </div>
        </form>

When I enter the search criteria and press Enter, it shows "not found" because the speciesName value is undefined.

How can I extract the speciesName value after entering it and clicking Enter to then insert it into the search method?

Answer №1

To enable databinding, ensure you include the [(ngModel)] attribute. No need to provide arguments for the function.

Here is an updated version of the HTML code:

<form class="form-inline" id="searchForm">
            <div class="form-group">
                <input class="form-control mr-sm-2" type="search" placeholder="Enter 
                    id="speciesNameSearch" name="speciesNameSearch" 
                    (keyup.enter)="getSearchResult()" [(ngModel)]="speciesName"  >
            </div>
        </form>

Below is the code for the component function:

// Setting up speciesname variable in the component
speciesName: string = "";

// Function to get search results
getSearchResult() {
    this.speciesService.getSearchResult(this.speciesName).subscribe(result => {
        this.speciesList = result.results;
    }, error => this.toastr.error(error.statusText, '', {
        timeOut: 3000
    }));
}

Answer №2

When passing a value from a form field, you can utilize the name attribute or use [(ngModel)]. Another option is to pass $event as a function argument and retrieve the value in the component using event.target.value.

An example of HTML code for this scenario would be:

 <form class="form-inline" id="searchForm">
        <div class="form-group">
            <input class="form-control mr-sm-2" type="search" placeholder="Enter Species Name ..."
                id="speciesNameSearch" name="speciesNameSearch" aria-label="Search"
                (keyup.enter)="getSearchResult($event)">
        </div>
    </form>

To handle this in the component file, make the following change :

getSearchResult(speciesName) {
this.speciesName = speciesName.target.value;
console.log("species name : ", this.speciesName);

}

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

Utilizing Selenium and Node Replay for Enhanced Automation

Struggling with integrating node-replay with selenium for running protractor tests on an angularjs app. The tests are executed using grunt: grunt protractor Initially, the tests were functioning properly. However, after adding node-replay and implem ...

Utilizing Dependency Injection in Controllers over Using Modules

In my mainApp module, I have various controllers, a filter, and a factory. The issue I'm encountering is that when I include a dependency like angularFileUpload in my module: angular.module('mainApp', ['angularFileUpload']) Sin ...

AngularJS ng-repeat nested loop allows you to iterate through an array

I am currently working with the following JSON data: { "ListNhomThanhTra": [ { "ListKeHoachThanhTra": [ { "ListDoiTuong": [ { "MA_DV_DUOC_TT": "DT01", ...

Unlock the Power of Typography in React with Material UI Styled Components

Exploring the world of material UI is a new experience for me. I am currently in the process of creating a styled component using Typography. Below is what I have attempted so far: import styled from 'styled-components'; import { FormGroup, ...

Unable to install @uirouter/angularjs using npm

Encountering an error while trying to npm install @uirouter/angularjs, the error message displayed is: npm ERR! code E404 npm ERR! 404 Not Found: @uirouter/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96f7f8f1e3faf7e4bfb9f8d ...

Toggle the selection of a div by clicking a button in AngularJS with a toggle function

I have several div elements on a webpage. Each div contains a button! When the button is clicked for the first time: The border color of the div will change to blue (indicating the div is now selected). The "ok" button will be hidden (leaving only t ...

Retrieve the $scope object within an isolated directive

Is there a way to modify a $scope variable from within an isolated directive? I've experimented with the '@, =, &' syntax in the directive scope but haven't been successful. Here's a simplified version of my code: JS app.co ...

Using a comma format while typing in Angular ensures that the input field

When using jqxwidget from here, the default format includes commas separated by underscores. I am looking to have the field empty initially, with commas appearing as the user types - similar to a F2 cell renderer. For example, typing 100 should display a ...

Upon initializing an Angular project from the ground up, I encountered an issue where a custom pipe I had created was not

After creating an Angular 16.1.0 application and a custom pipe, I encountered error messages during compilation. Here are the steps I took: Ran ng new exampleProject Generated a pipe using ng generate pipe power Modified the content of app.compone ...

PhpStorm flawlessly detects ES7 type hinting errors

For my project, I have implemented TypeScript. While JavaScript's array includes() function has been valid since ECMA6, setting the lib parameter in tsconfig to "es6" results in a non-fatal error being thrown in the browser console when using the foll ...

"Enhance User Interactions with Angular-ui Tooltips Featuring

I recently integrated bootstrap tooltips into my application. While the "normal" tooltips are working fine, I encountered an issue with tooltip-html-unsafe. It seems to display an empty tooltip. Here is my tooltip code: <a><span tooltip-placeme ...

Tips for sending JSON data via an HTTP POST request

Hello there! I am relatively new to programming and Angular. Within my controller, I have the following data: temanService.create({ Userid: $scope.datateman.userid, Address: $scope.datateman.address, Employeeid: $scope.datateman.employeeid, ...

Transform chosen images into a slideshow using Node.js and Angular JavaScript

I'm currently working on a project where I have an array of images being printed out in Angular, which I can select and download as a zip file. However, I now want to modify this functionality to create a slideshow instead. I've already imported ...

Oops! Looks like you forgot to provide a value for the form control named <name>. Make sure to fill

I have encountered an issue with a nested operation. The process involves removing an offer and then saving it again as a repeating one. However, the problem arises when I try to use patchValue() on the item in offerList[index] after saving the repeating ...

Issues arise when attempting to store data into an array with the assistance of FileReader

I am currently working on an Angular4 project where I am facing an issue with saving Blob data returned from my API call to an array of pictures in base64 format. This is so that I can later display the images using *ngFor. Here is the API call I am makin ...

Interested in halting the code execution once a match is found?

In Angular JS, I have developed a service method that checks whether any of the potential statuses in an array (pendingApplications) match any of the set statuses in another array (applicableStatuses). In order for this to function correctly, the method ...

Issue with Access Denied Error in Internet Explorer 11 when Using AngularJS

Every software development process consists of two essential components. FIRST, the hard work of developing the application. SECOND, the even harder task of making it compatible with the notorious Internet Explorer. Currently, we have an AngularJS (v1.3.1 ...

Implementing $rootScope Injection in an AngularJS Factory Function

I'm currently working with AngularJS code that utilizes a factory function called from a Directive to Post a file to a Web API. I am struggling with passing the key returned by the function to my controller. Can someone provide me with guidance on how ...

The html-duration-picker is not being displayed in the proper format

I've been working on integrating an external library that allows for inputting document length. Specifically, I'm using the html-duration-picker library, but it seems like the input functionality is not quite right for durations. Could it be th ...

What is the method to configure Angular to wait for the server to load session information data?

The server holds session information that is utilized in several controllers within my application. Is there a way to have Angular wait until the session has fully loaded during startup? ...