What is the best method for obtaining the li-Element in "Angular2 for TypeScript" (beta) so that I can apply a particular CSS class to it?

In my Angular2 application, I am working on creating a search functionality similar to Google's search where the results are displayed in a box. While I have successfully implemented this feature and it is functioning properly, one issue remains. When using the "key down" or "key up" keys after performing a search, the search results in the result box do not highlight like they do in Google.

Here is my current code:

<input type="search" class="form-control">

// resultbox
<div>
   <ul>
     <li *ngFor="#item of items">{{ item.text }}</li>
   </ul>
</div>

Please note that "items" represents the list of search results, which is displaying correctly. Now, I am looking for a way to dynamically highlight the specific <li> element that corresponds to the user's selection when navigating through the search results using the keyboard arrow keys.

My initial idea involves using an index counter to mark the selected <li> element with a unique class (e.g., "searchIndex") to change its color. However, I am unsure about how to implement this. Do you have a solution for achieving this highlighting effect? Alternatively, if you have a better suggestion for handling this scenario, I would appreciate your input.

I am hopeful that someone can provide guidance on this matter.

Answer №1

<input (keyup)="selectedItem--" (keydown)="selectedItem++">

<div>
   <ul>
     <li *ngFor="#item of items; #i=index" [class.selected]="i == selectedItem">{{ item.text }}</li>
   </ul>
</div>

You may want to implement some additional logic for when selectedItem < 0 or selectedItem >= numResult. Consider using an event handler function instead of the inline --/++ operators for better control. Hope this helps.

Update (in response to a question from the comments)

I have a quick question: Is there a way to remove the "selected" CSS property when hovering over the list? I'd like it to behave similar to Google where keyboard navigation selects an item, but hovering with the mouse removes the selection and activates hover style instead.

<div>
   <ul (mouseover)="isMouseover=true"
       (mouseout)="isMouseover=false">
     <li *ngFor="#item of items; #i=index" 
         [class.selected]="i == selectedItem && !isMouseover">{{ item.text }}</li>
   </ul>
</div>

Don't forget to add this field to your component:

isMouseover: boolean = false;

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 Jquery's prependTo method will add a display:block property to

Can't find a solution to this issue. This is the code snippet in question: var new_img = '<img id="' + drag_id + '" rel="' + drop_id + '" class="' + gallery_link + ' drop_out" src="' + drag_src + '" /& ...

integrating a CSS file into a Vue project

As a newcomer to Vue, I encountered some difficulties understanding how things function in Vue. One of the obstacles I faced was integrating my own custom CSS file into a project. I attempted to create a file called style.css within the src folder and add ...

The following error occurred: "Item cannot be serialized into JSON format."

I'm working on a Python code that looks like this: my_list=json.dumps(data_list) payload = {'data_list' : my_list} requests.get("http://127.0.0.1:8000/myhorizon/resource_usage/index", json=payload) After that, I use AJAX to create a curv ...

When compiling without the --aot flag, the matTable in Angular is causing an error stating "unable to read property 'find' of undefined."

An error is being thrown by the angular material table (matTable) when compiling without --aot. https://i.sstatic.net/i3qMF.png Although the application works fine when the target es version is set to es5, it heavily depends on es6 features. Therefore, i ...

Tips for arranging five images side-by-side in a row

I have a collection of 5 images: Image 1: Image 2: Image 3: Image 4: Image 5: The dimensions of each image are as follows: Image 1: 70x40 Image 2: 80x42 Image 3: 90x44 Image 4: 100x46 Image 5: 120x48 I would like to arrange these images ...

Ways to adjust the size of an HTML fieldset?

Is there a way to decrease the space between the paragraph and the border of this fieldset? I attempted to adjust the margins in the following manner: fieldset { margin: 1px; margin-top: 2px; border-top-right-radius: 1px; } <fieldset> < ...

Having troubles with Angular 2 subscription functionality?

I am attempting to launch a modal window that has its template and logic in a separate component. My goal is to accomplish this by subscribing to an observable, but I am encountering issues. Below is my code: Method within the component where I want to tr ...

Chrome is unable to establish a connection with the Java HTTP Server

Here is my basic HTTP Server setup: public class MyServer { public static void main(String [] args) throws IOException { Test t = null; int port = 9000; HttpServer server = HttpServer.create(new InetSocketAddress(port), 0) ...

How do I retrieve the value of a dxi-item in TypeScript with Angular and Devextreme?

One of the challenges I am facing is related to a Data Grid that has editing capabilities in popup mode. Within this grid, there are two data fields - password and confirm password - which I would like to validate to ensure they match. However, I am strugg ...

"Using jQuery to dynamically change the src attribute of an iframe, the change persists even after

There's a strange issue bothering me. On a single page, I have a menu and an iframe. Whenever I click on a menu button, the jQuery code changes the src attribute of the iframe. Initially, when the page loads, the iframe is supposed to display "Home". ...

What steps can be taken to avoid repetitive user creation in Firebase?

While developing an event app using the Ionic 4 framework with Firebase as the back-end, I ran into an issue with user creation on the Cloud Firestore database. Every time a user logs in using Google or Facebook, Firebase creates a new entry in the databas ...

When touch-triggered on IOS, HTML5 Web SQL Transactions were smoothly bypassed without any errors

I'm encountering issues with database transactions on IOS devices. When the user does not interact with the phone, everything functions as expected. However, if the user taps, scrolls, or touches the screen, some transactions bypass the actual transac ...

Creating seamless compatibility between the elliptic library in JavaScript and the ecdsa library in Golang for efficient cross-platform operations

I am having issues with validating a signature created using the elliptic JavaScript library and the ecdsa library from Golang. The elliptic curve in question is secp256k1. Below are some snippets of code: Here are the TypeScript utility functions: impor ...

What are the steps for implementing two Li elements in HTML with distinct attributes?

Usage I decided to utilize li elements in various ways on a single web page. I used them as part of a navbar at one point and then later repurposed them for an image grid. Issue The problem arises when the dropdown menu within the navbar is partially hid ...

Issue with Ionic3: When using ElementRef nativeElement.getElementsByClassName, the returned collection is inaccessible

I've been following a tutorial on Ionic and directives, and everything seems to be working fine except for one thing. When I try to retrieve the FAB element using ElementRef's nativeElement.getElementsByClassName method, it returns undefined. Str ...

The compilation of SCSS CSS is encountering an error with the provided CSS code

Upon compiling SCSS, I encountered an error with the following CSS: span.icon-hcp { filter: progid: DXImageTransform.Microsoft.AlphaImageLoader(src='../images/icon-hc.jpg', sizingMethod='scale') !important; -ms-filter: ...

Change object values to capital letters

Upon retrieving myObject with JSON.stringify, I am now looking to convert all the values (excluding keys) to uppercase. In TypeScript, what would be the best way to accomplish this? myObj = { "name":"John", "age":30, "cars": [ { "name":"Ford", ...

How can I retrieve the text content of a label within an option tag in HTML?

While extracting the text from a label in an option and storing them in a json format, this process could be beneficial. Here's an example: <datalist id="datalist1"> <option value="US" label="United States" /> <option value="UK" label= ...

Can Socket.IO link to a source tag that doesn't actually exist?

As I was following the 'Get started thing' tutorial on Socket.IO, I encountered a step that required me to add the socket.io.js script to my HTML page. The instruction provided was: /socket.io/socket.io.js However, when I checked my folders, I ...

There seems to be an issue with the <mat-form-field> where normal input functions correctly, but encounters an error when trying to use mat

I've searched through other inquiries, but none have provided the solution I am looking for. <mat-form-field> <mat-select matInput placeholder="Favorite food"> <mat-option *ngFor="let food of foods" [value]="food.value"> ...