Visão geral do componente Angular Badge
Angular Badge é um componente usado em conjunto com avatares, menus de navegação ou outros componentes em um aplicativo quando uma notificação visual é necessária. Os Badges geralmente são projetados como ícones com um estilo predefinido para comunicar informações, sucesso, avisos ou erros.
Angular Badge Example
Getting Started with Ignite UI for Angular Badge
Para começar a usar o componente Ignite UI for Angular Badge, 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 issoIgxBadgeModule no seu arquivo app.module.ts.
// app.module.ts
...
import { IgxBadgeModule } from 'igniteui-angular/badge';
// import { IgxBadgeModule } from '@infragistics/igniteui-angular'; for licensed package
@NgModule({
...
imports: [..., IgxBadgeModule],
...
})
export class AppModule {}
Alternativamente,16.0.0 você pode importar comoIgxBadgeComponent uma dependência independente.
// home.component.ts
...
import { IgxBadgeComponent } from 'igniteui-angular/badge';
// import { IgxBadgeComponent } from '@infragistics/igniteui-angular'; for licensed package
@Component({
selector: 'app-home',
template: '<igx-badge icon="check" type="success" shape="square"></igx-badge>',
styleUrls: ['home.component.scss'],
standalone: true,
imports: [IgxBadgeComponent]
})
export class HomeComponent {}
Now that you have the Ignite UI for Angular Badge module or component imported, you can start with a basic configuration of the igx-badge component.
Using the Angular Badge Component
Let's see how the demo sample is done. It's a simple success badge on an avatar. To build that, we need to import the IgxAvatarModule, along with the IgxBadgeModule:
// app.module.ts
...
import { IgxBadgeModule } from 'igniteui-angular/badge';
import { IgxAvatarModule } from 'igniteui-angular/avatar';
// import { IgxBadgeModule, IgxAvatarModule } from '@infragistics/igniteui-angular'; for licensed package
@NgModule({
...
imports: [..., IgxBadgeModule, IgxAvatarModule],
...
})
export class AppModule {}
Alternatively, as of 16.0.0 you can import the IgxBadgeComponent and IgxAvatarComponent as standalone dependencies.
Em seguida, adicionaremos esses componentes ao nosso modelo:
<div class="wrapper">
<igx-avatar icon="person" shape="circle" size="small"></igx-avatar>
<igx-badge icon="check" type="success"></igx-badge>
</div>
Usando o wrapper, posicionaremos o emblema de forma absoluta, cobrindo um pouco o avatar:
.wrapper {
position: relative;
margin-top: 15px;
}
igx-badge {
position: absolute;
bottom: 0;
left: 28px;
}
Badge Shape
We can change the badge shape through the shape attribute setting its value to square. By default, the shape of the badge is rounded.
<igx-badge icon="check" type="success" shape="square"></igx-badge>
Se tudo for feito corretamente, você deverá ver o exemplo de demonstração mostrado acima no seu navegador.
Badge Size
The size of the badge can be controlled using the --size variable. It will make sure that the badge sizes proportionally in both directions. Keep in mind, however, that badges containing text values use the caption typography style for its font-size and line-height. For that reason, when setting the --size of a badge containing text to values below 16px, you will also need to modify its typography.
Exemplo:
igx-badge {
--size: 12px;
font-size: calc(var(--size) / 2);
line-height: normal;
}
Badge Icon
In addition to material icons, the igx-badge component also supports usage of Material Icons Extended and any other custom icon set. To add an icon from the material icons extended set inside your badge component, first you have to register it:
export class BadgeIconComponent implements OnInit {
constructor (protected _iconService: IgxIconService) {}
public ngOnInit() {
this._iconService.addSvgIconFromText(heartMonitor.name, heartMonitor.value, 'imx-icons');
}
}
Depois, basta especificar o nome do ícone e a família da seguinte forma:
<igx-badge icon="heart-monitor" iconSet="imx-icons"></igx-badge>
Badge in List
Let's extend the previous sample and create a list with contacts, similar to those in chat clients. In addition to the contact name, we want to display an avatar and the current state of the contact (online, offline or away). To achieve this, we're using the igx-badge and igx-avatar components. For a container, igx-list is used.
Para continuar, inclua todos os módulos necessários e importe-os no arquivo app.module.ts.
// app.module.ts
...
import { IgxListModule } from 'igniteui-angular/list';
import { IgxAvatarModule } from 'igniteui-angular/avatar';
import { IgxBadgeModule } from 'igniteui-angular/badge';
// import { IgxListModule, IgxAvatarModule, IgxBadgeModule } from '@infragistics/igniteui-angular'; for licensed package
@NgModule({
...
imports: [..., IgxListModule, IgxAvatarModule, IgxBadgeModule],
})
export class AppModule {}
Note
The igx-badge has icon and type inputs to configure the badge look. You can set the icon by providing its name from the official material icons set. The badge type can be set to either default, info, success, warning, or error. Depending on the type, a specific background color is applied.
In our sample, icon and type are bound to model properties named icon and type.
Em seguida, adicionamos os contatos em nosso modelo:
<!-- contacts.component.html -->
<igx-list>
<igx-list-item isHeader="true">
Team Members (4)
</igx-list-item>
<igx-list-item *ngFor="let member of members">
<div class="wrapper">
<div>
<igx-avatar icon="person" shape="circle" size="small"></igx-avatar>
<igx-badge [icon]="member.icon" [type]="member.type" class="badge-style"></igx-badge>
</div>
<div class="contact-container">
<span class="contact-name">{{ member.name }}</span>
</div>
</div>
</igx-list-item>
</igx-list>
Vamos criar nossos membros no arquivo typescript assim:
// contacts.component.ts
...
public members: Member[] = [
new Member('Terrance Orta', 'online'),
new Member('Donna Price', 'online'),
new Member('Lisa Landers', 'away'),
new Member('Dorothy H. Spencer', 'offline'),
];
...
class Member {
public name: string;
public status: string;
public type: string;
public icon: string;
constructor(name: string, status: string) {
this.name = name;
this.status = status;
switch (status) {
case 'online':
this.type = 'success';
this.icon = 'check';
break;
case 'away':
this.type = 'warning';
this.icon = 'schedule';
break;
case 'offline':
this.type = 'error';
this.icon = 'remove';
break;
}
}
}
Posicione o emblema em seu contêiner pai:
/* contacts.component.css */
.wrapper {
display: flex;
flex-direction: row;
}
.contact-name {
font-weight: 600;
}
.contact-container {
margin-left: 20px;
}
.badge-style {
position: absolute;
bottom: 2.5px;
left: 40px;
}
Se o exemplo estiver configurado corretamente, uma lista de membros deverá ser exibida e cada membro terá um avatar e um emblema, mostrando seu estado atual.
Estilização
Badge Theme Property Map
Alterar a$background-color propriedade atualiza automaticamente as seguintes propriedades dependentes:
| Propriedade primária | Propriedade dependente | Descrição |
|---|---|---|
| $background cor | $icon cor | A cor usada para os ícones no distintivo. |
| $text-cor | A cor usada para o texto no distintivo. |
To get started with styling the badges, 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 badge-theme and accepts some parameters that style the badge's items. When you set the $background-color, the $icon-color and $text-color are automatically assigned based on which offers better contrast—black or white. Note that the $border-radius property only takes effect when the badge's shape is set to square.
$custom-badge-theme: badge-theme(
$background-color: #57a5cd,
$border-radius: 4px
);
To include the new theme we use the css-vars mixin:
@include css-vars($custom-badge-theme);
Demo
Styling with Tailwind
Você pode usarbadge nossas classes utilitárias personalizadas de Tailwind. Certifique-se de configurar o Tailwind primeiro.
Junto com a importação de vento de cauda em sua folha de estilo global, você pode aplicar os utilitários de tema desejados da seguinte maneira:
@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-badge,dark-badge.
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 do emblema. A sintaxe é a seguinte:
<igx-badge
class="!light-badge ![--background:#FF4E00] ![--border-radius:4px]">
</igx-badge>
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, seus distintivos devem ficar assim:
API References
- Componente IgxAvatar
- Componente IgxBadge
- Estilos de IgxBadgeComponent
- Componente de lista Igx
- Componente IgxListItem
- Tipo de emblema Igx
Theming Dependencies
Additional Resources
Nossa comunidade é ativa e sempre acolhedora para novas ideias.