https://github.com/bithost-gmbh/ngx-mat-select-search
Componente Angular que fornece um campo de entrada para pesquisar/filtrar opções MatSelect da biblioteca Angular Material.
Veja-o em ação em
https://stackblitz.com/github/bithost-gmbh/ngx-mat-select-search-example
veja código de exemplo, compilações no navegador, versão mais recente, versão mais recente do material
https://bithost-gmbh.github.io/ngx-mat-select-search/
pré-construído, versão mais recente, versão de material mais antiga, funciona em dispositivos móveis
Nota importante : Este projeto é uma implementação temporária de angular/components#5697. O objetivo é ter uma implementação no repositório oficial do Angular Material, um novo PR será criado.
Contribuições são bem-vindas, abra um problema e, de preferência, registre uma solicitação pull.
Nosso objetivo é fornecer o melhor serviço possível, melhorando constantemente NgxMatSelectSearch
e respondendo rapidamente aos relatórios de bugs. Fazemos isso totalmente gratuito. Se você acha que esta biblioteca foi útil para você e economizou um tempo precioso para você e sua empresa, considere fazer uma doação para apoiar sua manutenção e desenvolvimento.
Muito obrigado aos nossos apoiadores financeiros!
Philip Viktor Schulz-Klingauf |
Muito obrigado a todos os colaboradores da nossa comunidade!
Esteban Gehring | Markus Mächler | Tristão | Sirh3e | Tony H. | Michał Stawicki |
Aleix Ferré | Nulo | Chama Walker | Cristian Raducanu | Damião Miranda | Dane Vanderbilt |
David Sansome | Edgar Scheiermann | Erendis | Gustavo Miranda | Henno Lauinger | Nulo |
Iblis Lin | Jean-François Céré | Joe DeCock | Jomal Johny | Jonathan Kolberg | Kristof Gilis |
Melroy Van Den Berg | Muhammad Ahsan Ayaz | Ovidijus Stukas | Ray Suelzer | Roberto Pattis | Roland Broekema |
Sebastian Wierzbicki | Nulo | Stas Amasev | Thierry Nischelwitzer | Vlad Ioffe | Nulo |
Nulo | Josué | Nulo | Nulo |
Instale ngx-mat-select-search
em seu projeto:
npm install ngx-mat-select-search
Importe o NgxMatSelectSearchModule
, por exemplo, em seu app.module.ts
:
import { MatSelectModule } from '@angular/material' ;
import { NgxMatSelectSearchModule } from 'ngx-mat-select-search' ;
@ NgModule ( {
imports : [
...
MatSelectModule ,
NgxMatSelectSearchModule
] ,
} )
export class AppModule { }
Use o componente ngx-mat-select-search
dentro de um elemento mat-select
colocando-o dentro de um elemento <mat-option>
:
< mat-form-field >
< mat-select [formControl] =" bankCtrl " placeholder =" Bank " #singleSelect >
< mat-option >
< ngx-mat-select-search [formControl] =" bankFilterCtrl " > </ ngx-mat-select-search >
</ mat-option >
< mat-option *ngFor =" let bank of filteredBanks | async " [value] =" bank " >
{{bank.name}}
</ mat-option >
</ mat-select >
</ mat-form-field >
Veja os exemplos em https://github.com/bithost-gmbh/ngx-mat-select-search/tree/master/src/app/examples como conectar o ngx-mat-select-search
e filtrar as opções disponíveis. Ou dê uma olhada em https://github.com/bithost-gmbh/ngx-mat-select-search-example para vê-lo em um aplicativo independente.
Como alternativa, você pode usá-lo com formulários baseados em modelos da seguinte maneira:
< ngx-mat-select-search ngModel (ngModelChange) =" filterMyOptions($event) " >
Para alterar os rótulos, use as entradas especificadas na seção API da seguinte forma:
< ngx-mat-select-search [formControl] =" bankFilterCtrl "
placeholderLabel =" Find bank... "
noEntriesFoundLabel =" 'no matching bank found' " > </ ngx-mat-select-search >
Para usar a API i18n para tradução dos rótulos, adicione os atributos i18n-...
correspondentes:
< ngx-mat-select-search [formControl] =" bankFilterCtrl "
placeholderLabel =" Find bank... "
i18n-placeholderLabel
noEntriesFoundLabel =" 'no matching bank found' "
i18n-noEntriesFoundLabel > </ ngx-mat-select-search >
@angular/core
: ^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
@angular/material
: ^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
com MatSelectModule
( @angular/material/select
) 6.0.0
@angular/core
: ^15.0.0
@angular/material
: ^15.0.0
com MatLegacySelectModule
( @angular/material/legacy-select
) 5.0.0
@angular/core
: ^12.0.0 || ^13.0.0 || ^14.0.0
@angular/material
: ^12.0.0 || ^13.0.0 || ^14.0.0
3.3.3
@angular/core
: ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0 || ^12.0.0 || ^13.0.0
@angular/material
: ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0 || ^12.0.0 || ^13.0.0
1.8.0
@angular/core
: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0
@angular/material
: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0
O MatSelectSearchComponent
implementa a interface ControlValueAccessor. Além disso, fornece as seguintes entradas:
/** Label of the search placeholder */
@ Input ( ) placeholderLabel = 'Suche' ;
/** Type of the search input field */
@ Input ( ) type = 'text' ;
/** Font-based icon used for displaying Close-Icon */
@ Input ( ) closeIcon = 'close' ;
/** SVG-based icon used for displaying Close-Icon. If set, closeIcon is overridden */
@ Input ( ) closeSvgIcon ?: string ;
/** Label to be shown when no entries are found. Set to null if no message should be shown. */
@ Input ( ) noEntriesFoundLabel = 'Keine Optionen gefunden' ;
/**
* Whether the search field should be cleared after the dropdown menu is closed.
* Useful for server-side filtering. See [#3](https://github.com/bithost-gmbh/ngx-mat-select-search/issues/3)
*/
@ Input ( ) clearSearchInput = true ;
/** Whether to show the search-in-progress indicator */
@ Input ( ) searching = false ;
/** Disables initial focusing of the input field */
@ Input ( ) disableInitialFocus = false ;
/** Enable clear input on escape pressed */
@ Input ( ) enableClearOnEscapePressed = false ;
/**
* Prevents home / end key being propagated to mat-select,
* allowing to move the cursor within the search input instead of navigating the options
*/
@ Input ( ) preventHomeEndKeyPropagation = false ;
/** Disables scrolling to active options when option list changes. Useful for server-side search */
@ Input ( ) disableScrollToActiveOnOptionsChanged = false ;
/** Adds 508 screen reader support for search box */
@ Input ( ) ariaLabel = 'dropdown search' ;
/** Whether to show Select All Checkbox (for mat-select[multi=true]) */
@ Input ( ) showToggleAllCheckbox = false ;
/** Select all checkbox checked state */
@ Input ( ) toggleAllCheckboxChecked = false ;
/** select all checkbox indeterminate state */
@ Input ( ) toggleAllCheckboxIndeterminate = false ;
/** Display a message in a tooltip on the toggle-all checkbox */
@ Input ( ) toggleAllCheckboxTooltipMessage = '' ;
/** Define the position of the tooltip on the toggle-all checkbox. */
@ Input ( ) toggleAllCheckboxTooltipPosition: 'left' | 'right' | 'above' | 'below' | 'before' | 'after' = 'below' ;
/** Show/Hide the search clear button of the search input */
@ Input ( ) hideClearSearchButton = false ;
/**
* Always restore selected options on selectionChange for mode multi (e.g. for lazy loading/infinity scrolling).
* Defaults to false, so selected options are only restored while filtering is active.
*/
@ Input ( ) alwaysRestoreSelectedOptionsMulti = false ;
/**
* Recreate array of selected values for multi-selects.
*
* This is useful if the selected values are stored in an immutable data structure.
*/
@ Input ( ) recreateValuesArray = false ;
/** Output emitter to send to parent component with the toggle all boolean */
@ Output ( ) toggleAll = new EventEmitter < boolean > ( ) ;
Para personalizar o ícone de pesquisa, adicione ngxMatSelectSearchClear
ao seu item transparente personalizado (um mat-icon
ou qualquer outro elemento) e coloque-o dentro do componente ngx-mat-select-search
:
< ngx-mat-select-search >
< mat-icon ngxMatSelectSearchClear > delete </ mat-icon >
</ ngx-mat-select-search >
Se apenas o ícone precisar ser alterado, as entradas closeIcon
e closeSvgIcon
poderão ser usadas.
Para personalizar o elemento nenhuma entrada encontrada, adicione ngxMatSelectNoEntriesFound
ao seu item personalizado (um mat-icon, span, button
ou qualquer outro elemento) e coloque-o dentro do componente ngx-mat-select-search
:
< ngx-mat-select-search >
< span ngxMatSelectNoEntriesFound >
No entries found
< button mat-button color =" primary " >
Add < mat-icon > add </ mat-icon >
</ button >
</ span >
</ ngx-mat-select-search >
O conteúdo personalizado com a classe CSS mat-select-search-custom-header-content
pode ser transcluído da seguinte forma:
< ngx-mat-select-search >
< div class =" mat-select-search-custom-header-content " > something special </ div >
</ ngx-mat-select-search >
Fornecendo o InjectionToken MAT_SELECTSEARCH_DEFAULT_OPTIONS
, os valores padrão de várias propriedades @Input()
podem ser definidos globalmente. Consulte a documentação das propriedades @Input()
correspondentes de MatSelectSearchComponent
.
Exemplo:
import { MAT_SELECTSEARCH_DEFAULT_OPTIONS , MatSelectSearchOptions } from 'ngx-mat-select-search' ;
@ NgModule ( {
...
providers : [
{
provide : MAT_SELECTSEARCH_DEFAULT_OPTIONS ,
useValue : < MatSelectSearchOptions > {
closeIcon : 'delete' ,
noEntriesFoundLabel : 'No options found' ,
}
}
]
} )
class AppModule { }
Este projeto foi gerado com Angular CLI versão 1.7.1.
Execute ng serve
para um servidor de desenvolvimento. Navegue para http://localhost:4200/
. O aplicativo será recarregado automaticamente se você alterar algum dos arquivos de origem.
Execute ng build
para construir o projeto. Os artefatos de construção serão armazenados no diretório dist/
. Use o sinalizador -prod
para uma compilação de produção.
Execute npm run build-lib
para construir a biblioteca e gerar um pacote NPM. Os artefatos de construção serão armazenados na pasta dist-lib/
.
Para liberar, execute cd dist-lib/ && npm publish
.
Execute npm run test
para executar os testes de unidade via Karma.