Visão geral do componente do painel de expansão Angular
Ignite UI for Angular fornece aos desenvolvedores um dos componentes de layout mais úteis e fáceis de usar - o Expansion Panel. Este componente rico em recursos é usado para criar uma visualização de resumo detalhada expansível/recolhível. O conteúdo pode incluir animação Angular Expansion Panel, texto, ícones, cabeçalho, barra de ação e outros elementos.
Painel de Expansão Ignite UI igx-expansion-panel é um componente acordeão Angular leve que pode ser renderizado em dois estados - recolhido ou expandido. O Painel de Expansão no Angular pode ser alternado usando clique do mouse ou interações do teclado. Você também pode combinar vários Painéis de Expansão Angular no acordeão Angular.
Angular Expansion Panel Example
Criamos este simples Angular Expansion Panel Example usando Ignite UI Angular. Veja como o exemplo funciona.
Getting Started with Ignite UI for Angular Expansion Panel
Para começar a usar o componente Ignite UI for Angular Drop Down, 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 issoIgxExpansionPanelModule no seu arquivo app.module.ts.
// app.module.ts
...
import { IgxExpansionPanelModule } from 'igniteui-angular';
// import { IgxExpansionPanelModule } from '@infragistics/igniteui-angular'; for licensed package
@NgModule({
...
imports: [..., IgxExpansionPanelModule],
...
})
export class AppModule {}
Alternativamente,16.0.0 você pode importarIgxExpansionPanelComponent como uma dependência independente ou usar oIGX_EXPANSION_PANEL_DIRECTIVES token para importar o componente e todos os seus componentes e diretivas de suporte.
// home.component.ts
import { IGX_EXPANSION_PANEL_DIRECTIVES } from 'igniteui-angular';
// import { IGX_EXPANSION_PANEL_DIRECTIVES } from '@infragistics/igniteui-angular'; for licensed package
@Component({
selector: 'app-home',
template: `
<igx-expansion-panel>
<igx-expansion-panel-header>
<igx-expansion-panel-title>
Golden Retriever
</igx-expansion-panel-title>
<igx-expansion-panel-description>
Medium-large gun dog
</igx-expansion-panel-description>
</igx-expansion-panel-header>
<igx-expansion-panel-body>
The Golden Retriever is a medium-large gun dog that retrieves shot waterfowl,
such as ducks and upland game birds, during hunting and shooting parties.
The name "retriever" refers to the breed's ability to retrieve shot game undamaged due to their soft mouth.
Golden retrievers have an instinctive love of water, and are easy to train to basic or advanced obedience standards.
</igx-expansion-panel-body>
</igx-expansion-panel>
`,
styleUrls: ['home.component.scss'],
standalone: true,
imports: [IGX_EXPANSION_PANEL_DIRECTIVES]
/* or imports: [IgxExpansionPanelComponent, IgxExpansionPanelHeaderComponent, IgxExpansionPanelTitleDirective, IgxExpansionPanelDescriptionDirective, IgxExpansionPanelBodyComponent] */
})
export class HomeComponent {}
Now that you have the Ignite UI for Angular Expansion Panel module or directives imported, you can start using the igx-expansion-panel component.
Using the Angular Expansion Panel
A tabela abaixo mostra todas as partes de marcação disponíveis para o Painel de Expansão Angular.
| Nome da etiqueta | Descrição |
|---|---|
igx-expansion-panel |
O componente host - armazena o cabeçalho e o corpo. |
igx-expansion-panel-header |
Armazena o cabeçalho do componente. Ele está sempre visível. Armazena título e descrição, bem como qualquer conteúdo adicional |
igx-expansion-panel-title |
Use-o para definir o título do painel de expansão. |
igx-expansion-panel-description |
Pode ser usado para fornecer um breve resumo. A descrição sempre aparecerá após o título (se o título estiver definido). |
igx-expansion-panel-icon |
Use-o para alterar o ícone padrão de expansão/recolhimento. |
igx-expansion-panel-body |
Este é o contêiner expansível e só fica visível quando o painel é expandido. |
Properties Binding and Events
We can add some logic to our component to make it show/hide the igx-expansion-panel-description depending on the current state of the panel.
We can do this by binding the description to the control collapsed property:
// in expansion-panel.component.ts
import { IgxExpansionPanelComponent } from 'igniteui-angular';
// import { IgxExpansionPanelComponent } from '@infragistics/igniteui-angular'; for licensed package
@Component({...})
export class ExpansionPanelComponent {
@ViewChild(IgxExpansionPanelComponent, {read: IgxExpansionPanelComponent})
public panel: IgxExpansionPanelComponent;
}
<!-- in expansion-component.component.html -->
<igx-expansion-panel>
<igx-expansion-panel-header>
Golden Retriever
<igx-expansion-panel-description *ngIf="panel.collapsed">
Medium-large gun dog
</igx-expansion-panel-description>
</igx-expansion-panel-header>
...
</igx-expansion-panel>
O exemplo de código a seguir mostrará a descrição curta somente quando o componente estiver em seu estado recolhido. Se quisermos adicionar funcionalidades mais complexas dependendo do estado do componente, também podemos vincular a um emissor de evento.
// in expansion-panel.component.ts
@Component({...})
export class ExpansionPanelComponent {
...
public handleExpansion(args: {event: Event}): void {
... // Some functionality
}
}
<!-- in expansion-component.component.html -->
<igx-expansion-panel (onExpanded)="handleExpansion($event)" (contentCollapsed)="handleCollapse($event)"></igx-expansion-panel>
Abaixo temos os resultados:
Component Customization
The IgxExpansionPanelComponent allows for easy customization of the header.
Configuring the position of the header icon can be done through the iconPosition input on the igx-expansion-panel-header. The possible options for the icon position are left, right and none. The next code sample demonstrates how to configure the component's button to go on the right side.
<!-- in expansion-component.component.html -->
<igx-expansion-panel>
<igx-expansion-panel-header [iconPosition]="'right'"></igx-expansion-panel-header>
...
</igx-expansion-panel>
Note
The iconPosition property works with RTL - e.g. an icon set to show up in right will show in the leftmost part of the header when RTL is on.
The default icon for the toggle state of the control can be templated.
We can do that by passing content in an igx-expansion-panel-icon tag:
<!-- in expansion-component.component.html -->
<igx-expansion-panel>
<igx-expansion-panel-header [iconPosition]="'right'">
...
<igx-expansion-panel-icon>
<span class="example-icon" *ngIf="panel.collapsed">Show More</span>
<span class="example-icon" *ngIf="!panel.collapsed">Show Less</span>
</igx-expansion-panel-icon>
</igx-expansion-panel-header>
...
</igx-expansion-panel>
Nosso Painel de Expansão Angular agora exibirá "Mostrar Mais" quando o painel estiver recolhido e "Mostrar Menos" quando estiver totalmente expandido.
The IgxExpansionPanel control allows all sorts of content to be added inside of the igx-expansion-panel-body. It can render IgxGrids, IgxCombo, charts and even other expansion panels!
Para simplificar, vamos adicionar algumas marcações básicas ao corpo do nosso painel de expansão.
<!-- in expansion-panel.component.html -->
...
<igx-expansion-panel-body>
<div class="example-content">
<img [src]="imgSource" alt="dog-image">
The Golden Retriever is a medium-large gun dog that retrieves shot waterfowl, such as ducks and upland game birds, during hunting and shooting parties. The name "retriever" refers to the breed's ability to retrieve shot game undamaged due to their soft mouth. Golden retrievers have an instinctive love of water, and are easy to train to basic or advanced obedience standards.
<a igxButton="outlined" target="_blank" [href]="readMore">Read more</a>
</div>
</igx-expansion-panel-body>
...
Vamos ver o resultado de todas as mudanças acima:
Estilização
Expansion Panel Theme Property Map
Changing the $header-background and $body-background properties automatically updates the following dependent properties:
| Propriedade primária | Propriedade dependente | Descrição |
|---|---|---|
$header-contexto |
$header-título-cor | O cabeçalho do painel cor do texto do título. |
| $header-cor-ícone- | A cor do ícone do cabeçalho do painel. | |
| $header-descrição-cor | A cor do texto do cabeçalho do painel para descrição. | |
| $header-foco de fundo | O cabeçalho do painel foca a cor de fundo. | |
| $disabled-cor-texto | O painel desativou a cor do texto. | |
| $disabled-descrição-cor | O painel desativava a cor do texto da descrição do cabeçalho. | |
| $body-contexto | $body cor | Cor do texto do corpo do quadro. |
Palettes & Colors
Primeiro, criamos uma paleta personalizada que depois pode ser passada para nosso componente:
// In real life, this should be in our main sass file so we can share the palette between all components.
// In our case, it's in the component SCSS file "expansion-styling.component.scss".
@use "igniteui-angular/theming" as *;
// IMPORTANT: Prior to Ignite UI for Angular version 13 use:
// @import '~igniteui-angular/lib/core/styles/themes/index';
// Add your brand colors.
$my-primary-color:#353a4b;
$my-secondary-color: #ffd351;
$my-surface-color: #efefef;
// Create custom palette.
$my-color-palette: palette(
$primary: $my-primary-color,
$secondary: $my-secondary-color,
$surface: $my-surface-color
);
Creating the Component Theme
Now let's create our component theme and pass the $my-color-palette palette from the above sniped.
// In expansion-styling.component.scss
// Create expansion panel theme.
$custom-panel-theme: expansion-panel-theme(
// Styling parameters.
$header-background: color($my-color-palette, "primary", 700),
$header-focus-background: color($my-color-palette, "primary", 700),
$header-title-color: color($my-color-palette, "secondary"),
$header-icon-color: color($my-color-palette, "secondary"),
$body-background: color($my-color-palette, "primary", 700),
$body-color: color($my-color-palette, "secondary", 100),
$border-radius: .5
);
If we prefer instead of creating a palette, we can assign the colors directly to the expansion-panel-theme function as arguments. If the title-color, icon-color, or other foreground properties are not explicitly provided, they will be automatically assigned to either black or white - whichever offers better contrast with the background.
$custom-panel-theme: expansion-panel-theme(
$header-background: #353a4b,
$header-focus-background: #353a4b,
$header-title-color: #ffd351,
$header-icon-color: #ffd351,
...
);
Note
To see all the available parameters for styling trough the theming engine check the API documentation
Applying the Component Theme
Now to apply the component theme all that's left is to include css-vars mixin and pass the $custom-panel-theme map.
// In expansion-styling.component.scss
@include css-vars($custom-panel-theme);
To find out more on how you can use Ignite UI theming engine click here
Demo
Styling with Tailwind
Você pode estilizar o painel de expansão usando nossas classes utilitárias personalizadas 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-expansion-panel,dark-expansion-panel.
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 painel de expansão. A sintaxe é a seguinte:
<igx-expansion-panel
class="!light-expansion-panel
![--header-background:#4F6A5A]
![--body-background:#A3C7B2]"
>
...
</igx-expansion-panel>
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, seu painel de expansão deve ficar assim:
Angular Expansion Panel Animations
Using specific animation
It is possible to use other than default animation when expanding and collapsing the component.
Assuming the igxExpansionPanel is already imported in app.module.ts as previously described, you can create a custom animation setting object and set it to be used in the Ignite UI for Angular Expansion Panel. The approach requires the useAnimation method and the specific animations to be used so we start importing these and defining the animation settings like:
// in expansion-panel.component.ts
import { useAnimation } from '@angular/animations';
import { IgxExpansionPanelComponent, slideInLeft, slideOutRight } from 'igniteui-angular';
// import { IgxExpansionPanelComponent, slideInLeft, slideOutRight } from '@infragistics/igniteui-angular'; for licensed package
@Component({...})
export class ExpansionPanelComponent {
@ViewChild(IgxExpansionPanelComponent, {read: IgxExpansionPanelComponent})
public panel: IgxExpansionPanelComponent;
public animationSettingsCustom = {
closeAnimation: useAnimation(slideOutRight, {
params: {
duration: '100ms',
toPosition: 'translateX(25px)'
}
}),
openAnimation: useAnimation(slideInLeft, {
params: {
duration: '500ms',
fromPosition: 'translateX(-15px)',
startOpacity: 0.1
}
})
};
public collapsed() {
return this.panel && this.panel.collapsed;
}
}
As you can see, we are going to use slideInLeft and slideOutRight animations from our inbuilt suite of animations to make the component content appear more dramatically from the left side and disappear on the right when collapsing the content. In the process, we override some of the existing parameters with the specific ones we want to use.
The sample shows some user information and the key point here is passing the animation settings to the component like:
[animationSettings] = "animationSettingsCustom"
<!-- in expansion-panel.component.html -->
...
<igx-expansion-panel [animationSettings] = "animationSettingsCustom" class="my-expansion-panel">
<igx-expansion-panel-header>
<igx-expansion-panel-title class="sample-title">Angular</igx-expansion-panel-title>
</igx-expansion-panel-header>
<igx-expansion-panel-body>
Angular (commonly referred to as "Angular 2+" or "Angular v2 and above") is a TypeScript-based open-source web application framework led by the Angular Team at Google and by a community of individuals and corporations.
</igx-expansion-panel-body>
</igx-expansion-panel>
...
Você pode ver os resultados abaixo:
Multiple panel scenario
Veja o tópico igxAccordion
API Reference
- API do Painel de Expansão Igx
- API do IgxExpansionPanelHeader
- API do IgxExpansionPanelBody
- Estilos do IgxExpansionPanel