Descripción general del componente de la barra de navegación de Angular
The Ignite UI for Angular IgxNavbarComponent is an application header component that informs the user of their current position in an app, and helps them move back (much like the “back” button in a browser). The Navigation Bar can also provide links to quick actions such as search or favorite, helping users navigate smoothly through an application without trying to move to invalid routes or states. The bar sits at the top of the container it is placed in.
Angular Navbar Example
Getting Started with Ignite UI for Angular Navbar
Para comenzar con el componente Ignite UI for Angular Navbar, primero debe instalar Ignite UI for Angular. En una aplicación Angular existente, escriba el siguiente comando:
ng add igniteui-angular
Para obtener una introducción completa al Ignite UI for Angular, lea el tema de introducción.
The first step is to import the IgxNavbarModule inside our app.module.ts file.
// app.module.ts
import { IgxNavbarModule } from 'igniteui-angular/navbar';
// import { IgxNavbarModule } from '@infragistics/igniteui-angular'; for licensed package
@NgModule({
...
imports: [..., IgxNavbarModule],
...
})
export class AppModule {}
Alternativamente,16.0.0 puedes importarlosIgxNavbarComponent como una dependencia independiente, o usar elIGX_NAVBAR_DIRECTIVES token para importar el componente y todos sus componentes y directivas de soporte.
// home.component.ts
import { IGX_NAVBAR_DIRECTIVES } from 'igniteui-angular/navbar';
// import { IGX_NAVBAR_DIRECTIVES } from '@infragistics/igniteui-angular'; for licensed package
@Component({
selector: 'app-home',
template: '<igx-navbar title="Ignite UI for Angular"></igx-navbar>',
styleUrls: ['home.component.scss'],
standalone: true,
imports: [IGX_NAVBAR_DIRECTIVES],
/* or imports: [IgxNavbarComponent] */
})
export class HomeComponent {}
Now that you have the Ignite UI for Angular Navbar module or directives imported, you can start using the igx-navbar component.
Using the Angular Navbar
Luego en la plantilla de nuestro componente podemos agregar el siguiente código para mostrar una barra de navegación básica con un título:
<!--navbar.component.html-->
<igx-navbar title="Ignite UI for Angular"> </igx-navbar>
Add Menu Button
In order to add a menu button, we will show the action button using the actionButtonIcon property, and make it use a menu icon as follows:
<!--navbar.component.html-->
<igx-navbar title="Sample App" actionButtonIcon="menu" [isActionButtonVisible]="true"></igx-navbar>
Note
The actionButtonIcon uses the Material fontset by design.
Add Icon Buttons
Podemos hacer que nuestra aplicación sea un poco más funcional agregando opciones de búsqueda, favoritos y más. Para ello, tomemos los módulos IgxIconButton e IgxIcon e importémoslos en nuestro archivo app.module.ts.
// app.module.ts
...
import { IgxNavbarModule } from 'igniteui-angular/navbar';
import { IgxIconButtonDirective } from 'igniteui-angular/directives';
import { IgxIconModule } from 'igniteui-angular/icon';
// import { IgxNavbarModule, IgxButtonModule, IgxIconModule } from '@infragistics/igniteui-angular'; for licensed package
@NgModule({
...
imports: [..., IgxIconButtonDirective, IgxIconModule],
})
export class AppModule {}
A continuación, debemos actualizar nuestra plantilla con un botón de icono para cada una de las opciones que queremos que proporcione nuestra aplicación:
<!--navbar.component.html-->
<igx-navbar title="Sample App">
<button igxIconButton="flat">
<igx-icon>search</igx-icon>
</button>
<button igxIconButton="flat">
<igx-icon>favorite</igx-icon>
</button>
<button igxIconButton="flat">
<igx-icon>more_vert</igx-icon>
</button>
</igx-navbar>
Si todo ha ido bien deberías ver lo siguiente en tu navegador:
Add Custom Action
What if we want to use a custom template for our app navigation on the left-most part of the navbar? We can easily achieve this by using the igx-navbar-action directive, which will render the content we have provided. We will do that by using a button with the Font Awesome home icon.
/* navbar.component.css */
@import url("https://unpkg.com/@fortawesome/fontawesome-free-webfonts@^1.0.9/css/fontawesome.css");
@import url("https://unpkg.com/@fortawesome/fontawesome-free-webfonts@^1.0.9/css/fa-regular.css");
@import url("https://unpkg.com/@fortawesome/fontawesome-free-webfonts@^1.0.9/css/fa-solid.css");
<!--navbar.component.html-->
<igx-navbar title="Sample App">
<igx-navbar-action>
<button igxIconButton="flat">
<igx-icon family="fa" name="fa-home"></igx-icon>
</button>
</igx-navbar-action>
<button igxIconButton="flat">
<igx-icon>search</igx-icon>
</button>
<button igxIconButton="flat">
<igx-icon>favorite</igx-icon>
</button>
<button igxIconButton="flat">
<igx-icon>more_vert</igx-icon>
</button>
</igx-navbar>
Finalmente, así es como debería verse nuestra barra de navegación con su ícono de botón de acción personalizado:
Add Navigation Icon
If we want to create a navbar with an icon navigating back, we should follow a couple of steps. First, we can use the actionButtonIcon property to choose a suitable icon from the Material fontset. Then, we can make a simple check if there are any previously visited pages to go back to, and pass the result to the isActionButtonVisible property. The last step is to create a method for navigating back and hook it to the action property.
<!--navbar.component.html-->
<igx-navbar
title="Ignite UI for Angular"
actionButtonIcon="arrow_back"
[isActionButtonVisible]="canGoBack()"
(action)="navigateBack()"
>
</igx-navbar>
export class NavbarSample3Component {
constructor(private _location: Location) {}
public ngOnInit() {}
public navigateBack() {
this._location.back();
}
public canGoBack() {
return window.history.length > 0;
}
}
Si el ejemplo está configurado correctamente, debería ver lo siguiente en su navegador:
Note
If igx-navbar-action or igxNavbarAction is provided, the default actionButtonIcon will not be used.
Add Custom Title
If we want to provide a custom content for a navbar's title, we can achieve this by using igx-navbar-title or igxNavbarTitle directive. They will replace the default navbar's title provided by title input property. The sample below has a custom title containing a link with an image:
<!--navbar.component.html-->
<div class="sample-column">
<igx-navbar>
<igx-navbar-action>
<button igxIconButton="flat">
<igx-icon>menu</igx-icon>
</button>
</igx-navbar-action>
<div igxNavbarTitle>
<a href="https://es.infragistics.com/products/ignite-ui-angular" target="_blank">
<img
src="https://static.infragistics.com/marketing/Website/products/ignite-ui-landing/ignite-ui-logo.svg"
width="120px"
height="50px"
alt
style="margin-top: 7px;"
/>
</a>
</div>
<button igxIconButton="flat">
<igx-icon>search</igx-icon>
</button>
<button igxIconButton="flat">
<igx-icon>favorite</igx-icon>
</button>
<button igxIconButton="flat">
<igx-icon>more_vert</igx-icon>
</button>
</igx-navbar>
</div>
Note
If igx-navbar-title or igxNavbarTitle is provided, the default title will not be used.
Estilismo
Navbar Theme Property Map
Al modificar una propiedad principal, todas las propiedades dependientes relacionadas se actualizan automáticamente para reflejar el cambio:
| Propiedad principal | Propiedad dependiente | Descripción |
|---|---|---|
$background |
$text-color | El color del texto de la barra de navegación |
| $idle-icono-color | El color del icono de inactividad de la barra de navegación | |
| $hover-icono-color | El color del icono del cursor de la barra de navegación | |
| $border color (cambios solo para la variante índigo) | El color del borde de la barra de navegación | |
| $idle-icono-color | $hover-icono-color | El color del icono del cursor de la barra de navegación |
To get started with styling the navbar, 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 navbar-theme and provide just the $background and $idle-icon-color parameters. The theme will automatically compute all of the necessary background and foreground colors for various interaction states. If need, you can also manually override specific properties for finer control over the appearance.
$custom-navbar-theme: navbar-theme(
$background: #011627,
$idle-icon-color: #ecaa53,
);
Note
En lugar de codificar los valores de color como acabamos de hacer, podemos lograr mayor flexibilidad en cuanto a colores usando laspalette funciones ycolor. Por favor, consulta elPalettes tema para obtener una guía detallada sobre cómo utilizarlos.
The last step is to pass the newly created theme to the css-vars mixin:
@include css-vars($custom-navbar-theme);
Demo
Styling with Tailwind
Puedes diseñar la barra de navegación usando nuestras clases utilitarias personalizadas de Tailwind. Asegúrate de configurar primero a Tailwind.
Junto con la importación de viento de cola en su hoja de estilo global, puede aplicar las utilidades de tema deseadas de la siguiente manera:
@import "tailwindcss";
...
@use 'igniteui-theming/tailwind/utilities/material.css';
El archivo de utilidad incluye variantes tantolight comodark de tema.
- Usa
light-*clases para el tema ligero. - Usa
dark-*clases para el tema oscuro. - Añadir el nombre del componente después del prefijo, por ejemplo, ,
light-navbar,dark-navbar.
Una vez aplicadas, estas clases permiten cálculos dinámicos de temas. Desde ahí, puedes anular las variables CSS generadas usandoarbitrary properties. Después de los dos puntos, proporciona cualquier formato de color CSS válido (HEX, variable CSS, RGB, etc.).
Puedes encontrar la lista completa de propiedades en el tema de la barra de navegación. La sintaxis es la siguiente:
<igx-navbar class="!light-navbar ![--background:#7B9E89] ![--text-color:#121E17]" title="Sample App">
...
</igx-navbar>
Note
El signo de exclamación(!) es necesario para asegurar que la clase de utilidad tenga prioridad. Tailwind aplica estilos en capas y, sin marcar estos estilos como importantes, serán anulados por el tema predeterminado del componente.
Al final tu barra de navegación debería verse así:
API References
- Componente IgxNavbar
- IgxNavbarActionDirectiva
- IgxNavbarTitleDirective
- Estilos de componentes IgxNavbar
Componentes adicionales y/o directivas con API relativas que se utilizaron: