Visão geral do componente de navegação inferior Angular
O componente Ignite UI for Angular Bottom Navigation permite que o usuário navegue entre vários painéis de conteúdo exibidos em uma única visualização. A navegação pelos painéis é realizada com os botões de guia localizados na parte inferior do seu aplicativo.
Note
igx-tab-bar selector is deprecated. You could use igx-bottom-nav instead. IgxTabBarComponent class is renamed to IgxBottomNavComponent. IgxTabBarModule is renamed to IgxBottomNavModule.
Angular Bottom Navigation Example
Getting Started with Ignite UI for Angular Bottom Navigation
Para começar a usar o componente Ignite UI for Angular Bottom Navigation, primeiro você precisa instalar Ignite UI for Angular. Em um aplicativo Angular existente, digite o seguinte comando:
ng add igniteui-angular
Para obter uma introdução completa ao Ignite UI for Angular, leia o tópico de introdução.
O próximo passo é importar issoIgxBottomNavModule no seu arquivo app.module.ts.
// app.module.ts
...
import { IgxBottomNavModule } from 'igniteui-angular/bottom-nav';
// import { IgxBottomNavModule } from '@infragistics/igniteui-angular'; for licensed package
@NgModule({
...
imports: [..., IgxBottomNavModule],
...
})
export class AppModule {}
Alternativamente,16.0.0 você pode importarIgxBottomNavComponent como uma dependência independente ou usar oIGX_BOTTOM_NAV_DIRECTIVES token para importar o componente e todos os seus componentes e diretivas de suporte.
// home.component.ts
import { IGX_BOTTOM_NAV_DIRECTIVES } from 'igniteui-angular/bottom-nav';
import { IgxIconComponent } from 'igniteui-angular/icon';
// import { IGX_BOTTOM_NAV_DIRECTIVES, IgxIconComponent } from '@infragistics/igniteui-angular'; for licensed package
@Component({
selector: 'app-home',
template: `
<igx-bottom-nav>
<igx-bottom-nav-item>
<igx-bottom-nav-header>
<igx-icon>library_music</igx-icon>
</igx-bottom-nav-header>
<igx-bottom-nav-content>This is Item 1 content.</igx-bottom-nav-content>
</igx-bottom-nav-item>
<igx-bottom-nav-item>
<igx-bottom-nav-header>
<igx-icon>video_library</igx-icon>
</igx-bottom-nav-header>
<igx-bottom-nav-content>This is Item 2 content.</igx-bottom-nav-content>
</igx-bottom-nav-item>
<igx-bottom-nav-item>
<igx-bottom-nav-header>
<igx-icon>library_books</igx-icon>
</igx-bottom-nav-header>
<igx-bottom-nav-content>This is Item 3 content.</igx-bottom-nav-content>
</igx-bottom-nav-item>
</igx-bottom-nav>
`,
styleUrls: ['home.component.scss'],
standalone: true,
imports: [IGX_BOTTOM_NAV_DIRECTIVES, IgxIconComponent]
/* or imports: [IgxBottomNavComponent, IgxBottomNavItemComponent, IgxBottomNavHeaderComponent, IgxBottomNavContentComponent, IgxIconComponent] */
})
export class HomeComponent {}
Now that you have the Ignite UI for Angular Bottom Navigation module or directives imported, you can start using the igx-bottom-nav component.
Using the Angular Bottom Navigation
Our component's template includes the Bottom Navigation and three items. Each item wraps an igx-bottom-nav-header and an igx-bottom-nav-content component which represent respectively the header and the container of the data. Headers usually consist of an icon and an optional text label. The Bottom Navigation control is compatible with the Material Design Icons so to adopt them in your application simply add the Material+Icons import in your 'styles.css' file in the main application folder.
Note
If you haven't used the igx-icon in your application so far, please make sure to import the IgxIconModule in the app.module.ts before proceeding.
// styles.css
...
@import url('https://fonts.googleapis.com/icon?family=Material+Icons');
...
<igx-bottom-nav>
<igx-bottom-nav-item>
<igx-bottom-nav-header>
<igx-icon>library_music</igx-icon>
</igx-bottom-nav-header>
<igx-bottom-nav-content>This is Item 1 content.</igx-bottom-nav-content>
</igx-bottom-nav-item>
<igx-bottom-nav-item>
<igx-bottom-nav-header>
<igx-icon>video_library</igx-icon>
</igx-bottom-nav-header>
<igx-bottom-nav-content>This is Item 2 content.</igx-bottom-nav-content>
</igx-bottom-nav-item>
<igx-bottom-nav-item>
<igx-bottom-nav-header>
<igx-icon>library_books</igx-icon>
</igx-bottom-nav-header>
<igx-bottom-nav-content>This is Item 3 content.</igx-bottom-nav-content>
</igx-bottom-nav-item>
</igx-bottom-nav>
Se tudo correr bem, você deverá ver o exemplo de demonstração no seu navegador.
Customizing Bottom Navigation
Vamos modificar as abas adicionando rótulos ao lado dos ícones e garantir que os cabeçalhos estejam estilizados corretamente.
Primeiro, defina algumas matrizes de objetos para a fonte de dados no arquivo typescript do componente:
public songsList: object[] = [
{ title: 'Havana', artist: 'Camila Cabello' },
{ title: 'Meant To Be', artist: 'Bebe Rexha & Florida Georgia Line' },
{ title: 'New Rules', artist: 'Dua Lipa' },
{ title: 'Wolves', artist: 'Selena Gomez & Marshmello' }
];
public moviesList: object[] = [
{ title: 'Logan', genre: 'Action, Drama, Sci-Fi' },
{ title: 'Wonder Woman', genre: 'Action, Adventure, Fantasy' },
{ title: 'Guardians of the Galaxy Vol. 2', genre: 'Action, Adventure, Sci-Fi' },
{ title: 'Star Wars: The Last Jedi', genre: 'Action, Adventure, Fantasy' }
];
public booksList: object[] = [
{ title: 'Wonder', author: 'R. J. Palacio' },
{ title: 'Milk and Honey', author: 'Rupi Kaur' },
{ title: 'Giraffes Can\'t Dance', author: 'Jeff Kinne' },
{ title: 'The Getaway', author: 'Selena Gomez & Marshmello' }
];
Em seguida, atualize a marcação do modelo do componente da seguinte maneira:
<igx-bottom-nav>
<igx-bottom-nav-item>
<igx-bottom-nav-header>
<igx-icon igxBottomNavHeaderIcon>library_music</igx-icon>
<span igxBottomNavHeaderLabel>Songs</span>
</igx-bottom-nav-header>
<igx-bottom-nav-content>
<div class="item" *ngFor="let song of songsList">
<span class="item-line1">{{song.title}}</span><br/>
<span class="item-line2">{{song.artist}}</span>
</div>
</igx-bottom-nav-content>
</igx-bottom-nav-item>
<igx-bottom-nav-item>
<igx-bottom-nav-header>
<igx-icon igxBottomNavHeaderIcon>video_library</igx-icon>
<span igxBottomNavHeaderLabel>Movies</span>
</igx-bottom-nav-header>
<igx-bottom-nav-content>
<div class="item" *ngFor="let movie of moviesList">
<span class="item-line1">{{movie.title}}</span><br/>
<span class="item-line2">{{movie.genre}}</span>
</div>
</igx-bottom-nav-content>
</igx-bottom-nav-item>
<igx-bottom-nav-item>
<igx-bottom-nav-header>
<igx-icon igxBottomNavHeaderIcon>library_books</igx-icon>
<span igxBottomNavHeaderLabel>Books</span>
</igx-bottom-nav-header>
<igx-bottom-nav-content>
<div class="item" *ngFor="let book of booksList">
<span class="item-line1">{{book.title}}</span><br/>
<span class="item-line2">{{book.author}}</span>
</div>
</igx-bottom-nav-content>
</igx-bottom-nav-item>
</igx-bottom-nav>
You probably noticed that in addition to placing the icon and the span with the label between the item's header tags, we also attach the igxBottomNavHeaderIcon and the igxBottomNavHeaderLabel directives to them. These directives denote the respective elements and apply the proper styles to them.
Por fim, adicione as classes CSS usadas pelos elementos DIV e SPAN do modelo de conteúdo ao arquivo CSS do componente:
.item {
margin-bottom: 5px;
}
.item-line1 {
font-size: 14px;
color: gray;
}
.item-line2 {
font-size: 12px;
color: darkgray;
}
igx-bottom-nav-content {
padding: 10px;
}
Após essas modificações, nossa Navegação Inferior deverá ficar parecida com esta:
Se ter rótulos e ícones nos cabeçalhos não for o suficiente, você pode simplesmente adicionar seu conteúdo personalizado entre as tags de cabeçalho. Aqui está um exemplo:
<igx-bottom-nav>
<igx-bottom-nav-item>
<igx-bottom-nav-header>
<igx-icon igxBottomNavHeaderIcon>video_library</igx-icon>
<span igxBottomNavHeaderLabel>Movies</span>
<div>
<!-- your custom tab header content goes here -->
</div>
</igx-bottom-nav-header>
<igx-bottom-nav-content>
<h1>Tab content</h1>
</igx-bottom-nav-content>
</igx-bottom-nav-item>
</igx-bottom-nav>
Integration With Router Outlet Container
Apesar do uso primário do componente Bottom Navigation ser definir itens de aba com conteúdo, pode haver casos em que você precise definir itens de aba apenas com cabeçalhos. Provavelmente, o cenário principal para tal uso é a navegação entre visualizações usando o Angular Router. O exemplo a seguir demonstrará como configurar o componente Bottom Navigation para alternar entre três componentes em um único router-outlet.
To start we need a main component hosting the Bottom Navigation component and three view components with some content for demonstration purposes. For code snippets' simplicity, the view components will have a very short template but feel free to make them more distinguishable if you need. Also import these view components in your app.module.ts file.
// bottomnav-routing.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-bottomnav-routing',
styleUrls: ['bottomnav-routing.component.scss'],
templateUrl: 'bottomnav-routing.component.html'
})
export class BottomNavRoutingComponent { }
@Component({
template: '<p>Item 1 Content</p>'
})
export class BottomNavRoutingView1Component { }
@Component({
template: '<p>Item 2 Content</p>'
})
export class BottomNavRoutingView2Component { }
@Component({
template: '<p>Item 3 Content</p>'
})
export class BottomNavRoutingView3Component { }
The next step is to create the appropriate navigation mappings in the app-routing.module.ts file:
import { RouterModule, Routes } from '@angular/router';
import {
TabbarRoutingComponent,
TabbarRoutingView1Component,
TabbarRoutingView2Component,
TabbarRoutingView3Component,
} from './tabbar-routing.component';
const routes: Routes = [
{
path: '',
pathMatch: 'full',
redirectTo: '/tabbar-routing'
},
{
path: 'tabbar-routing',
component: TabbarRoutingComponent,
children: [
{ path: 'tabbar-view1', component: TabbarView1Component },
{ path: 'tabbar-view2', component: TabbarView2Component },
{ path: 'tabbar-view3', component: TabbarView3Component }
]
}
];
@NgModule({
exports: [ RouterModule ],
imports: [ RouterModule.forChild(routes) ]
})
export class TabbarRoutingModule { }
Agora que temos todas as rotas de navegação configuradas, precisamos declarar o componente BottomNavigation e configurá-lo para roteamento. Além disso, certifique-se de adicionar um router-outlet para renderizar a saída dos componentes de visualização.
<!-- bottomnav-routing.component.html -->
<router-outlet></router-outlet>
<igx-bottom-nav #tabs1>
<igx-bottom-nav-item
routerLinkActive
#rla1="routerLinkActive"
[selected]="rla1.isActive"
>
<igx-bottom-nav-header routerLink="tabbar-view1">
<igx-icon igxBottomNavHeaderIcon>phone</igx-icon>
</igx-bottom-nav-header>
</igx-bottom-nav-item>
<igx-bottom-nav-item
routerLinkActive
#rla2="routerLinkActive"
[selected]="rla2.isActive"
>
<igx-bottom-nav-header routerLink="tabbar-view2">
<igx-icon igxBottomNavHeaderIcon>supervisor_account</igx-icon>
</igx-bottom-nav-header>
</igx-bottom-nav-item>
<igx-bottom-nav-item
routerLinkActive
#rla3="routerLinkActive"
[selected]="rla3.isActive"
>
<igx-bottom-nav-header routerLink="tabbar-view3">
<igx-icon igxBottomNavHeaderIcon>format_list_bulleted</igx-icon>
</igx-bottom-nav-header>
</igx-bottom-nav-item>
</igx-bottom-nav>
The above code creates a BottomNavigation component with three tab items. All tab items are having the RouterLinkActive directive applied which tracks whether the linked route is currently active. Please, note, that the RouterLink directive is applied on the header element itself, not on the tab item. If any of these links becomes active, the corresponding tab item will have its selected property set because of the binding to the RouterLinkActive directive's isActive property. This way the selected tab item will always stay synchronized with the current browser's address.
A abordagem descrita acima é usada pelo exemplo a seguir para demonstrar o roteamento usando o componente BottomNavigation:
Styles
Bottom Nav Theme Property Map
Quando você modifica uma propriedade primária, todas as propriedades dependentes relacionadas são atualizadas automaticamente para refletir a alteração:
| Propriedade primária | Propriedade dependente | Descrição |
|---|---|---|
| $background | $label-cor | A cor da etiqueta usada em estado de repouso. |
| $label-cor | $icon cor | A cor do ícone usada em estado de repouso. |
| $label-desabilitado-cor | A cor desativada do selo. | |
| $icon cor | $label-cor | A cor da etiqueta usada em estado de repouso. |
| $label-desabilitado-cor | $icon-desabilitado-cor | A cor desativada do ícone. |
| $icon-desabilitado-cor | $label-desabilitado-cor | A cor desativada do selo. |
| $label-selecionada-cor | $icon-selecionada-cor | A cor do ícone usada no estado selecionado. |
| $icon-selecionada-cor | $label-selecionada-cor | A cor do rótulo usada no estado selecionado. |
To get started with styling the tabs, we need to import the index file, where all the theme functions and component mixins live:
@use "igniteui-angular/theming" as *;
// IMPORTANT: Prior to Ignite UI for Angular version 13 use:
// @import '~igniteui-angular/lib/core/styles/themes/index';
Following the simplest approach, we create a new theme that extends the bottom-nav-theme and accepts various parameters that allow us to style the tab groups.
$dark-bottom-nav: bottom-nav-theme(
$background: #292826,
$icon-selected-color: #f4d45c
);
Note
Em vez de codificar os valores de cor como acabamos de fazer, podemos alcançar maior flexibilidade em termos de cores usando aspalette funções e.color Por favor, consulte oPalettes tópico para orientações detalhadas sobre como usá-los.
If we take a look at the bottom-nav-theme, we will notice that there are even more parameters available to us in order to style our bottom navigation component!
Note
Para estilizar quaisquer componentes adicionais usados como parte do conteúdo de um item, um tema adicional deve ser criado específico para o respectivo componente.
O último passo é incluir o tema do componente em nosso aplicativo.
@include css-vars($dark-bottom-nav);
Demo
Styling with Tailwind
Você pode estilizar a navegação inferior usando nossas classes utilitárias personalizadas Tailwind. Certifique-se de configurar o Tailwind primeiro.
Junto com a importação Tailwind na sua folha de estilos global, você pode aplicar os utilitários de tema desejados da seguinte forma:
@import "tailwindcss";
...
@use 'igniteui-theming/tailwind/utilities/material.css';
O arquivo utilitário inclui tantolight as variantes quantodark as do tema.
- Use
light-*as aulas para o tema da luz. - Use
dark-*classes para o tema sombrio. - Adicione o nome do componente após o prefixo, por exemplo,
light-bottom-nav,dark-bottom-nav.
Uma vez aplicadas, essas classes possibilitam cálculos dinâmicos de temas. A partir daí, você pode sobrescrever as variáveis CSS geradas usandoarbitrary properties. Após os dois-pos, forneça qualquer formato de cor CSS válido (HEX, variável CSS, RGB, etc.).
Você pode encontrar a lista completa de propriedades no Tema IgxBottomNav. A sintaxe é a seguinte:
<igx-bottom-nav
class="!light-bottom-nav
![--background:#011627]
![--icon-selected-color:#FF8040]
![--label-selected-color:#FF8040]">
...
</igx-bottom-nav>
Note
O ponto de exclamação(!) é necessário para garantir que a classe utilitária tenha prioridade. O Tailwind aplica estilos em camadas e, sem marcar esses estilos como importantes, eles serão substituídos pelo tema padrão do componente.
No final, sua navegação inferior deve ficar assim:
API References
Theming Dependencies
Additional Resources
Nossa comunidade é ativa e sempre acolhedora para novas ideias.