Limiting the number of items shown in the dropdown panel of an NgSelect

Currently, I am utilizing Angular ngselect to showcase a dropdown menu with multiple options. However, due to the limited screen space, I need to restrict the number of items visible in the dropdown to about 3, allowing users to scroll through the rest.

Within a reactive form, I have integrated ng-select, and it appears as shown below:

Upon selecting the payment method, everything looks fine since there are only 2 items displayed.

However, upon choosing another option from the dropdown list, it gets cut off because the size exceeds the container's boundaries.

To address this issue, I attempted an alternative approach by appending the ng select dropdown to the body using appendTo="body".

When the dropdown appears using this method, it maintains its position rather than moving along with the ngselect element when I scroll through the page—resulting in some usability challenges.

My main concern is how to limit the number of elements displayed within the dropdown so that it fits snugly inside the container without any overflow issues.

Answer №1

Check out this issue on github

Here is an example of a bottom one

And you can see the version with checkbox here

This basic example shows only 4 items visible at once, achieved by using slice:0:4 in the *ngFor directive. The span below will display "more..." if there are more than 4 items selected.

<ng-select
    [items]="daysOfWeek"
    [multiple]="true"
    bindLabel="name"
    bindValue="order"
    placeholder="Select days"
    [(ngModel)]="selectedDays">
    <ng-template ng-multi-label-tmp let-items="items" let-clear="clear">
        <div class="ng-value" *ngFor="let item of items | slice:0:4">
            <span class="ng-value-label">{{item.name}}</span>
            <span class="ng-value-icon right" (click)="clear(item)" aria-hidden="true">×</span>
        </div>
        <div class="ng-value" *ngIf="items.length > 4">
            <span class="ng-value-label">{{items.length - 4}} more...</span>
        </div>
    </ng-template>
</ng-select>

Next, in the component file:

export class MultiSelectCustomExampleComponent implements OnInit {

    daysOfWeek: DayOfWeek[] = [];
    selectedDays: DayOfWeek[] = [];

    constructor() {
    }

    ngOnInit() {
        this.daysOfWeek = [
            new DayOfWeek("Monday", 1),
            new DayOfWeek("Tuesday", 2),
            new DayOfWeek("Wednesday", 3),
            new DayOfWeek("Thursday", 4),
            new DayOfWeek("Friday", 5),
            new DayOfWeek("Saturday", 6),
            new DayOfWeek("Sunday", 7),
        ];
    }
}

Lastly, here is the model for the list:

export class DayOfWeek {

    name: string;
    order: number;
    
    constructor(name: string, order: number) {
        this.name = name;
        this.order = order;
    }
}

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

Angular 2 routing malfunctioning

I'm encountering an issue while setting up routing in my application. The error displayed in the console is as follows: angular2-polyfills.js:138 Error: XHR error (404 Not Found) loading http://localhost:9000/angular2/router.js(…) Below is the co ...

Is the regex returning the correct result?

I need to discuss the date field with a format of YYYYMMDD, as shown below: zod.string().max(8).regex(new RegExp('^(19[0-9][0-9]|20[0-9][0-9]|[0-1][0-9]{3})(1[0-2]|0[1-9])(3[01]|[0-2][1-9]|[12]0)$')); The value provided is 20001915. The definit ...

An issue occurred during the compilation of an Angular6 project

I am embarking on my first Angular project and may not grasp every detail perfectly. In my search for guidance, I came across the command "ng build --prod" on Google and decided to give it a try. Everything seemed to be going smoothly at first until an err ...

Troubleshooting a Missing Angular (8) Pipe Error in Your Ionic 4 Application

Despite seeing similar questions posted here, none have provided a solution to my issue. I believe I am implementing it correctly, but clearly something is not right. In the app I'm developing with Ionic 4, I need to add a key to a URL in a gallery. ...

Tips for extracting the chosen text during a 'change' event

I need to access the text of the currently selected object. When I use $(this).text(), I end up getting all available selections I have attempted the following methods without achieving the desired result: $(this).text() $(this).selected() $(this).se ...

Navigating within components using code is an essential skill when working with Vue Router

I am currently developing a Quasar application powered by Vue 3 with vue-router version 4 All my routes are properly configured and function well when navigating from a component template using <router-link to="/route">Go to route</rout ...

Easy steps for importing node modules in TypeScript

I'm currently navigating the world of TypeScript and attempting to incorporate a module that is imported from a node module. I have chosen not to utilize webpack or any other build tools in order to maintain simplicity and clarity. Here is the struct ...

What steps should I follow to set up a TypeScript project that incorporates JavaScript modules compiled from PureScript?

TL;DR I am looking to develop TypeScript typings for compiled PureScript modules and include them in my npm package. I am willing to manually maintain these typings, but I am struggling with the configuration needed in tsconfig.json (up and downstream) and ...

SolidJS directives utilizing use:___ result in TypeScript errors when used in JSX

As I work on converting the forms example from JS to TS, I came across a typescript error related to directives in HTML: It appears that validate and formSubmit are being recognized as unused variables by typescript, resulting in the following jsx error: ...

Locate and retrieve the item that appears most often in a given array

In order to determine the mode of an array consisting of integer numbers only, I must create a function named findMode. If the array is empty, the function should return 0. Otherwise, it should return the element that occurs most frequently in the array. I ...

How can I combine Angular's material drag and drop feature with virtual scrolling?

I've been attempting to combine Angular material's virtual scrolling with drag and drop functionality, but I'm encountering an issue where the items are reverting back and the dragging and dropping doesn't seem to work as expected. Bel ...

The dropdown menus in Bootstrap are expanding outside the screen when opened

When I click on the dropdown in the Navbar on the right side, the menus open up far to the right and are not visible until I scroll horizontally. Here is the code snippet: <nav class="navbar navbar-expand-lg navbar-light bg-light"> < ...

The declaration module in Typescript with and without a body

I am facing an issue with importing a .mdx file. When I include the following in my mdx.d.ts: /// <reference types="@mdx-js/loader" /> import { ComponentType } from "react"; declare module '*.mdx' { const Component: ...

"Utilizing aws-sdk in a TSX file within a React project: a step-by

When working on a project using TypeScript (tsx) for React, I encountered an issue with uploading images to the server using aws-sdk to communicate with Amazon S3. To resolve this, I made sure to install aws-sdk via npm and typings. UploadFile.tsx import ...

The custom validation in nestjs is throwing an error due to an undefined entity manager

I've been working on developing a custom validation for ensuring unique values in all tables, but I encountered this error: ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'getRepository') TypeError: Cannot read proper ...

Typescript error: Cannot assign type 'undefined' to type 'string | number | symbol'

I need help figuring out how to address a TypeScript error in my code. Here's the scenario: export type status = 'success' | 'error' | undefined; There is an object that maps to different icons based on the status. const iconsMap: ...

Load page with sorted column in PrimeNg's <ptable> element

Utilizing primeNg's <p-table> component to showcase data in the following structure: HTML <p-table [value]="documents"> <ng-template pTemplate="header"> <tr> <th [pSortableColumn]="&apos ...

Creating dynamic and engaging videos using Angular with the ability to make multiple requests

I am facing an issue while working with videos in Angular. I am fetching the video URLs from an API to embed them in my application using the sanitazer.bypassSecurityTrustResourceUrl function provided by Angular. The videos are being displayed correctly wi ...

Incorporate a personalized Cypress function for TypeScript implementation

I'm in the process of developing a custom cypress command that will enable me to post a file using formData, as the current cy.request does not yet support formData. For the actual POST operation, I am utilizing request-promise-native. To begin with ...

Looking for a regular expression to verify if the URL inputted is valid in TypeScript

After conducting thorough research, I discovered that none of the suggested URLs met my criteria, prompting me to raise a new query. Here are my specific requirements: * The URL may or may not include 'http' or 'https' * The URL can co ...