Customize the height of the Angular Material autocomplete dropdown to meet your needs

Context

I have been working on a customized autocomplete feature using Angular Material, and I need to adjust the height of the dropdown results box for better visibility.

Exploration

After conducting some research, I discovered that Angular Material currently does not provide built-in support for modifying the height of the autocomplete dropdown. However, there are discussions and possible solutions available for Angular Material 2 (which will be compatible with AngularJS2):

Despite some suggestions about manipulating CSS styles (Angular Material Design Layout custom sizes) as a workaround, I haven't been successful in implementing these workarounds effectively.

Code Snippets

The project consists of an index.html, autocomplete.js, and server.js files along with mockData.json file.

Below are excerpts from the index.html, autocomplete.js, and style.css files. You can view the live demo hosted on Cloud9 if the server is active:

Additionally, here are snippets from the server.js file and the contents of the mockData.json file.

Query

Is there a way to increase the height of the dropdown box displaying autocomplete results?

Answer №1

One way to customize the number of dropdown items in an Angular Material autocomplete is by using the undocumented parameter md-dropdown-items:

<md-autocomplete 
    md-selected-item="selectedItem" 
    md-search-text="searchText" 
    md-items="item in getMatches(searchText)"
    md-item-text="item.display"
    md-dropdown-items="10">
        <span md-highlight-text="searchText">{{item.display}}</span>
</md-autocomplete>

The default value for this parameter is 5.

If you want to dynamically adjust the number of dropdown items based on window height, you can do so by setting it in your controller:

<md-autocomplete
    md-selected-item="selectedItem"
    md-search-text="searchText"
    md-items="item in getMatches(searchText)"
    md-item-text="item.display"
    md-dropdown-items="nbItems">
       <span md-highlight-text="searchText">{{item.display}}</span>
</md-autocomplete>

Then, define the value of nbItems in your controller, like this:

$scope.nbItems = 5 + $mdMedia('(min-height: 400px)') * 5 + $mdMedia('(min-height: 600px)') * 10;

This setup will display 5 items if the height is less than 400px, 10 items if less than 600px, and 20 items if greater than 600px.

I hope this explanation helps!

Just a reminder: the md-dropdown-items parameter only works for md-autocomplete, not for md-select.

It's a shame that it doesn't work for md-select too ;)

Answer №2

Origins

Following extensive trial and error, I have uncovered a workaround that addresses the issue at hand.

The so-called fix I've devised is more of a clever hack than a definitive solution. Unfortunately, official support for this particular problem is nonexistent, especially in Angular Material 1 which has been deprecated to pave the way for Angular Material 2 without ongoing maintenance.

Solution Overview

My workaround centers around an approach shared on GitHub, effectively overriding the default CSS settings with the following snippet:

.md-virtual-repeat-container.md-autocomplete-suggestions-container {
    height: 24vh;
    min-height: 12vh;
    max-height: 24vh !important;
}

Dive Deeper

This code circumvents the standard CSS rules by utilizing the !important declaration and specifying custom height values, predominantly using the vh unit but adaptable to px or any other metric.

While effective for a single autocomplete dropdown or uniform dropdowns throughout, conflicting implementations may emerge if dealing with disparate autocompletes due to the blanket override applied to all instances.

Closing Thoughts

Admittedly imperfect, this workaround remains serviceable as long as excessive customization isn't required within the autocomplete functionality.

I trust this insight proves beneficial to those encountering similar challenges down the line!

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

Shorten a data point in JSON code

I'm currently in the process of developing a stock widget that utilizes JSON to retrieve data from the Yahoo API/YQL console. I am specifically working with values extracted from the key ChangePercentRealtime, however, the values are longer than what ...

Manipulate a table using Jquery's find() method to insert a cell populated with information from an array using before()

My current challenge involves inserting a column of cells with data from an array. Despite attempting to use a for loop, all the cells end up displaying the same data from the array. What I really want is for each new cell to show 'row_header1', ...

Glitch in JavaScript: Converting Text to Numbers

My current challenge involves converting text into numbers using code. Here is the code snippet I have: var vals= ["a","b","c","d","e","f","g","h","i","j", ...

The addDays method cannot be used with date variables

Having two TextBoxes where I input 2 dates and try to retrieve an array of dates between them. Here is the code I'm using: $(".txtto").change(function () { var dates = new Array(); var dateto = new Date(); ...

What could be causing Vuejs to not update elements promptly?

Currently, I am encountering a scenario where I am adding options to a select element using Vue.js when the @change event of that specific element is triggered. An issue arises where the new option is not 'registered' until I exit the function. ...

Tips for using Jquery to round up currency values

Is there a way to round up various currencies using jQuery? I have a specific requirement: 10.30 → 10 //Round down if below .5 10.60 → 11 //Round up if after .5 849.95 → 850 1,022.20 → 1022 ...

Group by month and calculate the total sum using mongoose in MongoDB

I'm currently working with the orderdetails model in my project. Here is a snippet of the schema: const model = new Schema( { district: { type: String }, category: String, producer: String, variety: String, qty: String, price ...

Using CSS grid can allow for paragraphs to overlap on top of each

https://i.sstatic.net/LVsgQ.jpgCurrently working on constructing a biography page filled with text content, and I aim to utilize CSS GRID instead of floats. I encountered an issue in getting the text to occupy all the available white space within the layou ...

Transfer an object for reusability in a different JavaScript file without utilizing the default operator

I have a scenario where I have two files organized in a tree structure that defines an object. The first file is called common.js. export default { table: { actions: { save: 'Save', delete: 'Delete', update: ...

Making if-else statements easier

Greetings! I have a JSON data that looks like this: { "details": { "data1": { "monthToDate":1000, "firstLastMonth":"December", "firstLa ...

Tips for creating a menu that stays fixed to the page even when positioned absolutely

I'm currently working on creating a navbar that needs to be positioned to touch the edges of the screen. Here is the CSS code snippet that I have implemented so far: nav { position: absolute; top: 0; left: 0; right: 0; height:65px; displa ...

Switch between classes when hovering over / exiting ngFor elements

Displayed below is an element created using ngFor <span *ngFor="let picture of pictures; let i = index"> <a target="_blank" href="{{picture.image}}" class="thumbnail-display image-overlay"> <span class="overlay-icon hide"> ...

The average calculation malfunctioning after adjusting the input data

I am a beginner with AngularJS and facing an issue. I have a list of cities for which I need to calculate the average temperature. However, after editing the temperature values in the city list, the function that computes the average temperature is giving ...

Deleting a product category along with all its products: Understanding the basics of CRUD操作

I am looking for a way to delete a product category along with all the products within it. The Product model has a reference to the category as an object. Is there a straightforward method or a commonly used technique for this? I attempted to use removeAl ...

The Ionic search bar will only initiate a search once the keyboard is no longer in view

In my Ionic application, I have implemented a search bar to filter and search through a list. The filtering process is triggered as soon as I start typing in the search bar. However, the updated results are not displayed on the screen until I manually hide ...

Utilize Meteor and Mongo to access a nested array object in a template with spacebars

I am trying to populate the content of a textarea by extracting data from a nested array. In my helper function, I have specified the document id and the element id. The goal is to extract the content of the text field from the findOne result and display i ...

Receive a 404 error message while navigating through routes in Laravel

I recently came across an interesting tutorial by David Mosher on integrating Angular JS end-to-end. You can check it out on YouTube: http://www.youtube.com/watch?v=hqAyiqUs93c. However, I encountered a bit of trouble while trying to route the /auth/login ...

Steps to calculate the total number of rows in a datatable

I have implemented a datatable in my project, and I need to find out the total number of rows in the table when it is loaded. Here's the snippet of code I am currently using: $(document).ready( function() { $('#jobSearchResultTable').data ...

Tips on how to make content slide upwards

Need help with sliding menus? I have a solution for you. One issue is that the top menu option slides down instead of up. Let's fix it. Menu Code: <div class="additional-navigation-wrapper"> <div class="additional-navigation"> ...

Having trouble with closing the window on Mozilla and Chrome? Keep getting a scripting error message?

To close this window, click <a onclick="self.close();" href="#">here</a>. This is the code I am using. When I submit in Chrome and Mozilla, an error occurs. The error message is: "Script must not be allowed to close a window that was not o ...