Socket
Socket
Sign inDemoInstall

mt-select-dropdown

Package Overview
Dependencies
7
Maintainers
1
Versions
24
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    mt-select-dropdown

The MtSelectDropdown multi select dropdown library is a versatile Angular component designed to facilitate the creation of custom dropdowns and select menus within Angular applications. It offers a wide range of features and customization options, allowin


Version published
Weekly downloads
1
decreased by-88.89%
Maintainers
1
Install size
317 kB
Created
Weekly downloads
 

Readme

Source

mt-select-dropdown

mt-select-dropdown is a versatile and customizable Angular component that provides a dropdown interface for selecting single or multiple options.

mt-select-dropdown Key Features:

  1. Customization Options: The library provides extensive customization options for styling various elements of the dropdown, including the container, input field, selected items, dropdown menu, and more. Developers can apply custom CSS classes to achieve the desired visual appearance.

  2. Full Keyboard Navigation: Dropdowm support full keyboard Navigation.

  3. Multi-Select Support: The MtSelectDropdown component supports multi-select functionality, allowing users to select multiple items from a dropdown list. Selected items are visually highlighted and can be easily managed.

  4. Lazy Loading: With support for lazy loading, the library enables efficient handling of large datasets by loading items dynamically as the user scrolls through the dropdown list. This enhances performance and reduces initial loading times, especially for datasets with a large number of items.

  5. Search Functionality: Users can quickly search and filter dropdown options using the built-in search functionality. As users type in the search input field, the dropdown list dynamically updates to display matching results, providing a seamless user experience.

  6. Inbuilt API Calling: The library simplifies data fetching from external APIs by providing inbuilt API calling functionality. Developers can specify an API endpoint, and the library handles the HTTP requests and data processing, seamlessly integrating external data sources into the dropdown component.

  7. Event Handling: The library offers comprehensive event handling capabilities, allowing developers to define custom behavior for various events such as dropdown opening, closing, item selection, and more. This enables developers to create interactive dropdowns with rich user interactions.

  8. Error Handling: Robust error handling mechanisms are built into the library to gracefully handle errors that may occur during data fetching or interaction with external APIs. Error messages are displayed to users, providing informative feedback and enhancing the overall usability of the component.

Installation

$ npm install mt-select-dropdown

Dependencies

mt-select-dropdown requires Bootstrap 5 or above to function properly. It is listed as a peer dependency, so you'll need to install it separately along with mt-select-dropdown:

npm install bootstrap 

Import and Usage:

import { Component } from '@angular/core';
import { MtSelectDropdownComponent } from 'mt-select-dropdown';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [MtSelectDropdownComponent],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss'
})
export class AppComponent {
  title = 'MtSelectDropdown-app';

  selectedOption = [
    { id: 1, name: 'India' },
    { id: 2, name: 'USA' },
    { id: 3, name: 'JAP' },
    { id: 4, name: 'PUK' },
    { id: 5, name: 'RAT' },
    { id: 6, name: 'PAT' },
  ]
}

Options

The Mt-Select-Dropdown component provides various configuration options to customize its behavior:

Option NameTypeDefault ValueDescription
optionsany[][]Array of options to be displayed in the dropdown.
compareKeystring'id'The key to use when comparing options for selection.
labelKeystring'name'The key to use for displaying the label of each option.
batchLimitnumber-The maximum number of selected options to display in multi-select mode bwfore.
selectedItemTempletTemplateRef-Custom template for rendering selected items.
listItemTempletTemplateRef-Custom template for rendering items in the dropdown list.
willAutoClosebooleantrueFlag indicating whether the dropdown should automatically close when clicking outside.
isMultiSelectbooleanfalseFlag to enable multi-select mode.
placeholderstring'Please Select'Placeholder text to display when no option is selected.
sCOStyleClassOptions{}Style class options to customize the appearance of the dropdown and its items.
attachToBodybooleanfalseFlag to indicate whether the dropdown should be attached to the body.
lazyLoadingbooleanfalseFlag to enable lazy loading of options if apiPath provided then it will handle the api also.
addNotFoundbooleanfalseFlag to add a "Not Found" option when searching.
apiPathstring''The API path for lazy loading options.
limitnumber10The maximum number of options to fetch from the API at once.
pagenumber1The page number to fetch options from when using lazy loading.
order_bystring'name'The field to use for sorting options when fetching from the API.
order_directionstring'asc'The direction of sorting options when fetching from the API ('asc' or 'desc').
searchTextstring''The search query to filter options when using lazy loading.
parentIdValueanynullThe key of the parent ID used in API requests for lazy loading like is im loding cities and i want that to be filter by state then parentIdValue may be state_id.
parentIdanynullThe parent ID used in API requests for lazy loading e.g if i want cities of Ladakh then give Ladakh id in my DB.
selectedIdsanynullThe selected IDs used in API requests for lazy loading this will be given by component so that you can write a logic of sorting the selected on top.
selectedIdKeystring'id'The key to use for selected IDs in API requests for lazy loading.
otherParentIdanynullAnother parent ID used in API requests for lazy loading.
otherParentIdValueanynullThe value of the other parent ID used in API requests for lazy loading.

Demo

Demo

Basic Usage Example

<mt-select-dropdown
  [options]="options"
  [formControlName]="myControl"
  [onSelect]="onSelectMyControl">
</mt-select-dropdown>

Usage of Custom Templet

   <div class="row">
      <div class="col-md-12">
          <label class="form-label"> Partcipant<span class="text-danger">*</span></label>
          <div class="input-group mb-3">
              <div type="text" class="form-control form-control-sm">
                  <mt-select-dropdown [attachToBody]="true" [listItemTemplet]="partcipantListItem" [selectedItemTemplet]="partcipantSelectedItem" formControlName="partcipant" [isMultiSelect]="true"
                      [batchLimit]="2" [options]="options" class=""></mt-select-dropdown>
              </div>
              <span class="input-group-text"><i class="fa fa-plus"></i></span>
          </div>
          <ng-template #partcipantListItem let-option="option">
              <div class="row">
                  <div class="col-md-12">
                      <label class="form-label">{{option.name}}</label>
                  </div>
                  <div class="col-md-6">
                      <label class="form-label">{{option.email}}</label>
                  </div>
                  <div class="col-md-6">
                      <label class="form-label">{{option.phone}}</label>
                  </div>
              </div>
          </ng-template>

          <ng-template #partcipantSelectedItem let-option="option">
              <div class="row">
                  <div class="col-md-12">
                      <label class="form-label">{{option.name}}({{option.email}})</label>
                  </div>
              </div>
          </ng-template>
      </div>
  </div>

Usage Example of LazyLoding with Without Api

    <mt-select-dropdown
      [options]="options"
      [lazyLoading]="true"
      (onSearch)="loadOptions($event)"
      (loadNext)="loadMoreOptions()">
    </mt-select-dropdown>

Usage Example of LazyLoding with Api

<div class="col-md-6 mb-4">
    <label class="form-label">State<span class="text-danger">*</span></label>
    <mt-select-dropdown class="w-100" [order_by]="'id'" [lazyLoading]="true" [attachToBody]="true"
        formControlName="stateId" [apiPath]="url+'/state_dropdown'" class=""></mt-select-dropdown>
</div>

Configuration for LazyLoding with Api

  import {
    HttpClient,
  } from '@angular/common/http';
  import { MtSelectDropdownService } from 'mt-select-dropdown';

  @Injectable({
    providedIn: 'root',
  })
  export class HttpService {
    constructor(private http: HttpClient, private dropdownService: MtSelectDropdownService) {
      dropdownService.setHttpClient(http);//need to pass http client this will be used by component for http request
    }
  }

In Component we do this This is internal service

import { HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, throwError } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class MtSelectDropdownService {

  http: any;

  constructor() { }

  setHttpClient(http: any) {
    this.http = http
  }
}

We call the Api Like this internally

myService = inject(MtSelectDropdownService);

callApi(isMarge: boolean = false, searchText: string = '') {
    return new Promise((resolve, reject) => {
      try {
        this.loadingOptions = true;
        const lazyLoadingOptions = {
          limit: this.limit,
          page: this.page,
          order_by: this.order_by,
          order_direction: this.order_direction,
          searchText: this.searchText,
          parentIdValue: this.parentIdValue,
          parentId: this.parentId,
          selectedIds: this.selectedIds == null || this.selectedIds == undefined ? null : this.selectedIds,
          selectedIdKey: this.selectedIdKey,
          otherParentId: this.otherParentId,
          otherParentIdValue: this.otherParentIdValue,
          q: searchText
        }
        this.myService.post(this.apiPath, { ...lazyLoadingOptions })
          .subscribe({
            next: (list: any) => {
              if (list?.status == 1) {
                if (!list?.nextPage) this.isMorepage = false;
                this.page += 1;
                if (isMarge) {
                  this.options = [...this.options, ...list?.data];
                  for (let index = 0; index < list.data.length; index++) {
                    const element = list.data[index];
                    this.filteredOptions.push(element)
                  }
                }
                else { this.options = list?.data; this.filteredOptions = this.options; }
                this.loadingOptions = false;
                if (!this.filteredOptions.length && searchText) {
                  this.addNotFoundToList(searchText)
                }
                resolve(list)
              }
            },
            error: (e: any) => {
              this.loadingOptions = false;
              reject(e)
            },
          });
      } catch (e) {
        reject(e)
      }
    })
  }

Api Request Object

Your Endpoint will Recive request body like this

 {
      "limit": 10,
      "page": 1,
      "order_by": "id",
      "order_direction": "asc",
      "searchText": "",
      "parentIdValue": null,
      "parentId": null,
      "selectedIds": null,
      "selectedIdKey": "id",
      "otherParentId": null,
      "otherParentIdValue": null,
      "q": ""
  }

Api Response Object

The Api Response Object should be like this

{
    "status": 1,
    "previousPage": null,
    "currentPage": 1,
    "nextPage": 2,
    "total": 31,
    "limit": 10,
    "data": [
        {
            "id": 1,
            "name": "Ladakh",
            "code": "LD",
            "countryId": null,
            "createdAt": "2024-02-13T11:54:25.000Z",
            "updatedAt": "2024-02-13T11:54:25.000Z"
        },
    ],
  }

Events

The Mt-Select-Dropdown library emits several events to communicate changes and interactions with the parent component:

Event NameTypeDescription
onSelectEventEmitter<anyany[]>
onOpenEventEmitterEmit when the dropdown is opened.
onCloseEventEmitterEmit when the dropdown is closed.
onSearchEventEmitterEmit the search query when the user performs a search.
loadNextEventEmitterEmit to load the next batch of options in lazy loading mode.

Methods

The Mt-Select-Dropdown component provides several methods to interact with the dropdown programmatically:

Method SignatureDescription
writeValue(value: anyany[]): void
registerOnChange(fn: any): voidRegister change callback.
registerOnTouched(fn: any): voidRegister touched callback.
setDisabledState(isDisabled: boolean): voidSet the disabled state of the control.

StyleClassOptions

The StyleClassOptions interface defines the available CSS classes that can be applied to customize the appearance of the dropdown and its elements.

PropertyDescriptionDefault Value
dropdown_containerCSS class for styling the dropdown containerN/A
dropdown_form_controlCSS class for styling the custom input divN/A
selectedContainerCSS class for styling the selected options container in multi-select modeN/A
selectedItemCSS class for styling the selected option item in multi-select modeN/A
unselectItemCSS class for styling the unselect item (cross) in multi-select modeN/A
placeholderCSS class for styling the placeholder textN/A
dropSymbolCSS class for styling the drop symbolN/A
dropdownMenuCSS class for styling the dropdown menuN/A
searchInputCSS class for styling the search input in the dropdownN/A
dropdownItemCSS class for styling the dropdown items in the listN/A
<mt-select-dropdown
  [options]="options"
  [sCO]="styleClassOptions"
  [formControlName]="myControl"
  [onSelect]="onSelectMyControl">
</mt-select-dropdown>

Authors

  • Mohd Taqi - All Work Done By - Mohd Taqi

License

MIT License © Mohd Taqi

Keywords

FAQs

Last updated on 19 Feb 2024

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc