Filtro de pesquisa de grade Angular
Angular pesquisa em grade permite o processo de localização de valores na coleta de dados. Facilitamos a configuração dessa funcionalidade e ela pode ser implementada com caixa de entrada de pesquisa, botões, navegação por teclado e outros recursos úteis para uma experiência de usuário ainda melhor. Embora os navegadores forneçam nativamente a funcionalidade de pesquisa de conteúdo, na maioria das vezes o Grid virtualiza suas colunas e linhas que estão fora de exibição. Nesses casos, a pesquisa em grade nativa não consegue pesquisar dados nas células virtualizadas, pois elas não fazem parte do DOM. Estendemos a Ignite UI for Angular grade baseada em tabela com uma API de pesquisa que permite pesquisar o conteúdo virtualizado da Grid.
Angular Search Example
O exemplo a seguir representa Grid com caixa de entrada de pesquisa que permite pesquisar em todas as colunas e linhas, bem como opções de filtragem específicas para cada coluna.
Angular Search Usage
Grid setup
Vamos começar criando nossa grade e vinculando-a aos nossos dados. Também adicionaremos alguns estilos personalizados para os componentes que usaremos!
<!--searchgrid.component.html-->
<igx-grid #grid1 id="grid1" [data]="data" [autoGenerate]="false" [allowFiltering]="true">
<igx-column [field]="'IndustrySector'" dataType="string" [sortable]="true"></igx-column>
<igx-column [field]="'IndustryGroup'" dataType="string" [sortable]="true"></igx-column>
<igx-column [field]="'SectorType'" dataType="string" [sortable]="true"></igx-column>
<igx-column [field]="'KRD'" dataType="number" [sortable]="true"></igx-column>
<igx-column [field]="'MarketNotion'" dataType="number" [sortable]="true"></igx-column>
<igx-column [field]="'Date'" dataType="date" [sortable]="true"></igx-column>
</igx-grid>
/* searchgrid.component.css */
.grid__wrapper {
margin: 15px;
}
.offset {
margin-bottom: 15px;
}
.resultsText {
font-size: 0.875rem;
}
.chips {
margin-left: 5px;
}
.searchButtons {
margin-left: 5px;
}
Ótimo, e agora vamos nos preparar para a API de pesquisa do nosso Grid! Podemos criar algumas propriedades, que podem ser usadas para armazenar o texto pesquisado no momento e se a pesquisa diferencia maiúsculas de minúsculas e/ou por uma correspondência exata.
// searchgrid.component.ts
public searchText: string = '';
public caseSensitive: boolean = false;
public exactMatch: boolean = false;
Angular search box input
Now let's create our search input! By binding our searchText as ngModel to our newly created input and subscribe to the ngModelChange event, we can detect every single searchText modification by the user. This will allow us to use the Grid's findNext and findPrev methods to highlight all the occurrences of the searchText and scroll to the next/previous one (depending on which method we have invoked).
Both the findNext and the findPrev methods have three arguments:
text: string (the text we are searching for)- (optional)
caseSensitive: boolean (should the search be case sensitive or not, default value is false) - (optional)
exactMatch: boolean (should the search be by an exact match or not, default value is false)
Ao pesquisar por uma correspondência exata, a API de pesquisa destacará como resultados apenas os valores de célula que correspondem inteiramente ao searchText, levando em consideração também a diferenciação de maiúsculas e minúsculas. Por exemplo, as strings 'software' e 'Software' são uma correspondência exata com um desrespeito à diferenciação de maiúsculas e minúsculas.
Os métodos acima retornam um valor numérico (o número de vezes que o Grid contém a string fornecida).
<!--searchgrid.component.html-->
<input #search1 id="search1" placeholder="Search" [(ngModel)]="searchText" (ngModelChange)="grid.findNext(searchText, caseSensitive, exactMatch)" />
Display results count
Let's also display the position of the current occurrence, along with the total results count! We can do this by using the grid's lastSearchInfo property. This property is automatically updated when using the find methods.
- The
grid.lastSearchInfo.matchInfoCache.lengthvalue will give us the total results count. - The
grid.lastSearchInfo.activeMatchIndexvalue will give us the index position of the current occurrence (match).
<!--searchgrid.component.html-->
<div class="resultsText" *ngIf="grid.lastSearchInfo">
<span *ngIf="grid.lastSearchInfo.matchInfoCache.length > 0">
{{ grid.lastSearchInfo.activeMatchIndex + 1 }} of {{ grid.lastSearchInfo.matchInfoCache.length }} results
</span>
<span *ngIf="grid.lastSearchInfo.matchInfoCache.length == 0">
No results
</span>
</div>
Add search buttons
In order to freely search and navigate among our search results, let's create a couple of buttons by invoking the findNext and the findPrev methods inside the buttons' respective click event handlers.
<!--searchgrid.component.html-->
<div class="searchButtons">
<input type="button" value="Previous" (click)="grid.findPrev(searchText, caseSensitive, exactMatch)" />
<input type="button" value="Next" (click)="grid.findNext(searchText, caseSensitive, exactMatch)" />
</div>
Add keyboard search
We can also allow the users to navigate the results by using the keyboard's arrow keys and the Enter key. In order to achieve this, we can handle the keydown event of our search input by preventing the default caret movement of the input with the preventDefault() method and invoke the findNext/findPrev methods depending on which key the user has pressed.
<!--searchgrid.component.html-->
<input #search1 id="search1" placeholder="Search" [(ngModel)]="searchText" (ngModelChange)="grid.findNext(searchText, caseSensitive, exactMatch)"
(keydown)="searchKeyDown($event)" />
// searchgrid.component.ts
public searchKeyDown(ev) {
if (ev.key === 'Enter' || ev.key === 'ArrowDown' || ev.key === 'ArrowRight') {
ev.preventDefault();
this.grid.findNext(this.searchText, this.caseSensitive, this.exactMatch);
} else if (ev.key === 'ArrowUp' || ev.key === 'ArrowLeft') {
ev.preventDefault();
this.grid.findPrev(this.searchText, this.caseSensitive, this.exactMatch);
}
}
Case sensitive and Exact match
Now let's allow the user to choose whether the search should be case sensitive and/or by an exact match. For this purpose we can use simple checkbox inputs by binding our caseSensitive and exactMatch properties to the inputs' checked properties respectively and handle their change events by toggling our properties and invoking the findNext method.
<!--searchgrid.component.html-->
<span>Case sensitive</span>
<input type="checkbox" [checked]="caseSensitive" (change)="updateSearch()">
<span>Exact match</span>
<input type="checkbox" [checked]="exactMatch" (change)="updateExactSearch()">
// searchgrid.component.ts
public updateSearch() {
this.caseSensitive = !this.caseSensitive;
this.grid.findNext(this.searchText, this.caseSensitive, this.exactMatch);
}
public updateExactSearch() {
this.exactMatch = !this.exactMatch;
this.grid.findNext(this.searchText, this.caseSensitive, this.exactMatch);
}
Persistence
What if we would like to filter and sort our Grid or even to add and remove records? After such operations, the highlights of our current search automatically update and persist over any text that matches the searchText! Furthermore, the search will work with paging and will persist the highlights through changes of the Grid's perPage property.
Adding icons
Usando alguns de nossos outros componentes, podemos criar uma interface de usuário enriquecida e melhorar o design geral de toda a nossa barra de pesquisa! Podemos ter um bom ícone de pesquisa ou exclusão à esquerda da entrada de pesquisa, alguns chips para nossas opções de pesquisa e alguns ícones de design de material combinados com belos botões de estilo ondulado para nossa navegação à direita. Podemos envolver esses componentes dentro de um grupo de entrada para um design mais refinado. Para fazer isso, vamos pegar os módulos IgxInputGroup,IgxIcon,IgxRipple,IgxButton e IgxChip.
// app.module.ts
...
import {
IgxGridModule,
IgxInputGroupModule,
IgxIconModule,
IgxRippleModule,
IgxButtonModule,
IgxChipsModule
} from 'igniteui-angular';
// import {
// IgxInputGroupModule,
// IgxIconModule,
// IgxRippleModule,
// IgxButtonModule,
// IgxChipsModule
// } from '@infragistics/igniteui-angular'; for licensed package
@NgModule({
...
imports: [..., IgxInputGroupModule, IgxIconModule, IgxRippleModule, IgxButtonModule, IgxChipsModule],
})
export class AppModule {}
Por fim, vamos atualizar nosso modelo com os novos componentes!
We will wrap all of our components inside an IgxInputGroup. On the left we will toggle between a search and a delete/clear icon (depending on whether the search input is empty or not). In the center, we will position the input itself. In addition, whenever the delete icon is clicked, we will update our searchText and invoke the Grid's clearSearch method to clear the highlights.
<!--searchgrid.component.html-->
<igx-input-group type="search" class="offset">
<igx-prefix>
<igx-icon *ngIf="searchText.length == 0">search</igx-icon>
<igx-icon *ngIf="searchText.length > 0" (click)="clearSearch()">clear</igx-icon>
</igx-prefix>
<input #search1 id="search1" igxInput placeholder="Search" [(ngModel)]="searchText" (ngModelChange)="grid.findNext(searchText, caseSensitive, exactMatch)"
(keydown)="searchKeyDown($event)" />
<igx-suffix *ngIf="searchText.length > 0">
...
</igx-suffix>
</igx-input-group>
// searchgrid.component.ts
public clearSearch() {
this.searchText = '';
this.grid.clearSearch();
}
À direita, em nosso grupo de entrada, vamos criar três contêineres separados com as seguintes finalidades:
- Para exibir os resultados da pesquisa.
<!--searchgrid.component.html-->
<igx-suffix *ngIf="searchText.length > 0">
<div class="resultsText" *ngIf="grid.lastSearchInfo">
<span *ngIf="grid.lastSearchInfo.matchInfoCache.length > 0">
{{ grid.lastSearchInfo.activeMatchIndex + 1 }} of {{ grid.lastSearchInfo.matchInfoCache.length }} results
</span>
<span *ngIf="grid.lastSearchInfo.matchInfoCache.length == 0">
No results
</span>
</div>
</igx-suffix>
- Para exibir alguns chips que alternam as propriedades caseSensitive e exactMatch. Substituímos as caixas de seleção por dois chips elegantes que mudam de cor com base nessas propriedades. Sempre que um chip é clicado, invocamos seu respectivo manipulador -updateSearch ou updateExactSearch, dependendo de qual chip foi clicado.
<!--searchgrid.component.html-->
...
<div class="chips">
<igx-chips-area>
<igx-chip (click)="updateSearch()" [color]="caseSensitive? 'lightgrey' : 'rgba(0, 0, 0, .04)'">
<span>Case Sensitive</span>
</igx-chip>
<igx-chip (click)="updateExactSearch()" [color]="exactMatch? 'lightgrey' : 'rgba(0, 0, 0, .04)'">
<span>Exact Match</span>
</igx-chip>
</igx-chips-area>
</div>
...
- For the search navigation buttons, we have transformed our inputs into ripple styled buttons with material icons. The handlers for the click events remain the same - invoking the
findNext/findPrevmethods.
<!--searchgrid.component.html-->
<igx-suffix>
<div class="searchButtons">
<button igxIconButton="flat" igxRipple igxRippleCentered="true" (click)="grid.findPrev(searchText, caseSensitive, exactMatch)">
<igx-icon fontSet="material">navigate_before</igx-icon>
</button>
<button igxIconButton="flat" igxRipple igxRippleCentered="true" (click)="grid.findNext(searchText, caseSensitive, exactMatch)">
<igx-icon fontSet="material">navigate_next</igx-icon>
</button>
</div>
</igx-suffix>
Known Limitations
| Limitação | Descrição |
|---|---|
| Pesquisando em células com um modelo | Os destaques da funcionalidade de pesquisa funcionam apenas para os modelos de célula padrão. Se você tiver uma coluna com modelo de célula personalizado, os destaques não funcionarão, então você deve usar abordagens alternativas, como um formatador de coluna, ou definir osearchable propriedade na coluna como falsa. |
| Virtualização Remota | A pesquisa não funcionará corretamente ao usar virtualização remota |
| Células com texto cortado | Quando o texto na célula é muito grande para caber e o texto que estamos procurando é cortado pelas reticências, ainda rolaremos até a célula e a incluiremos na contagem de correspondências, mas nada será destacado |
API References
Neste artigo, implementamos nossa própria barra de pesquisa para o Grid com algumas funcionalidades adicionais quando se trata de navegar entre os resultados da pesquisa. Também usamos alguns componentes Ignite UI for Angular adicionais, como ícones, chips e entradas. A API de pesquisa está listada abaixo.
IgxGridComponent methods:
IgxGridCell methods:
IgxColumnComponent properties:
Componentes e/ou diretivas adicionais com APIs relativas que foram usadas:
- Componente do grupo de entrada Igx
- Componente IgxIcon
- Diretiva IgxRipple
- Diretiva IgxButton
- Componente IgxChip
Styles:
- Estilos IgxGridComponent
- Estilos de IgxInputGroupComponent
- Estilos IgxIconComponent
- Estilos IgxRippleDirective
- Estilos de IgxButtonDirective
- Estilos IgxChipComponent
Additional Resources
- Visão geral da grade
- Virtualização e desempenho
- Filtragem
- Paginação
- Classificação
- Resumos
- Movimentação de Colunas
- Fixação de coluna
- Redimensionamento de colunas
- Escolha