Descripción general de los componentes del panel de expansión de Angular

    Ignite UI for Angular proporciona a los desarrolladores uno de los componentes de diseño más útiles y fáciles de usar: el Panel de expansión. Este componente rico en funciones se utiliza para crear una vista de resumen detallada expandible o contraíble. El contenido puede incluir Angular animación del panel de expansión, texto, iconos, encabezado, barra de acciones y otros elementos.

    Ignite UI panel de expansión igx-expansion-panel es un componente de acordeón de Angular liviano que se puede renderizar en dos estados: colapsado o expandido. El panel de expansión de Angular se puede alternar mediante un clic del mouse o interacciones con el teclado. También puede combinar varios paneles de expansión Angular en Angular acordeón.

    Angular Expansion Panel Example

    Hemos creado este sencillo ejemplo de panel de expansión de Angular utilizando Ignite UI Angular. Vea cómo funciona el ejemplo.

    Getting Started with Ignite UI for Angular Expansion Panel

    Para comenzar con el componente Ignite UI for Angular DropDown, 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.

    El siguiente paso es importarlosIgxExpansionPanelModule en tu archivo 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 puedes importarlosIgxExpansionPanelComponent como una dependencia independiente, o usar elIGX_EXPANSION_PANEL_DIRECTIVES token para importar el componente y todos sus componentes y directivas de soporte.

    // 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

    En la siguiente tabla se muestran todas las piezas de marcado disponibles para el panel de expansión Angular.

    Nombre de etiqueta Descripción
    igx-expansion-panel El host del componente: almacena el encabezado y el cuerpo.
    igx-expansion-panel-header Almacena el encabezado del componente. Esto siempre es visible. Almacena el título y la descripción, así como cualquier contenido adicional.
    igx-expansion-panel-title Úselo para configurar el título del panel de expansión.
    igx-expansion-panel-description Se puede utilizar para proporcionar un breve resumen. La descripción siempre aparecerá después del título (si el título está configurado).
    igx-expansion-panel-icon Úselo para cambiar el ícono predeterminado de expandir/contraer.
    igx-expansion-panel-body Este es el contenedor expandible y solo es visible cuando el panel está 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>
    

    El siguiente ejemplo de código mostrará la breve descripción solo cuando el componente esté contraído. Si queremos agregar una funcionalidad más compleja según el estado del componente, también podemos vincularnos a un emisor de eventos.

    // 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>
    

    A continuación tenemos los 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>
    

    Nuestro Angular Panel de Expansión ahora renderizará "Mostrar Más" cuando el panel esté colapsado y "Mostrar Menos" una vez que esté completamente 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!

    En aras de la simplicidad, agreguemos algunas marcas básicas al cuerpo de nuestro panel de expansión.

    <!-- 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>
    ...
    

    Veamos el resultado de todos los cambios anteriores:

    Estilismo

    Expansion Panel Theme Property Map

    Changing the $header-background and $body-background properties automatically updates the following dependent properties:

    Propiedad principal Propiedad dependiente Descripción
    $header-antecedentes
    $header-título-color El color del texto del título del encabezado del panel.
    $header-icono-color El color del icono de cabecera del panel.
    $header-descripción-color El encabezado del panel, descripción del color.
    $header-enfoque-fondo El encabezado del panel enfoca el color de fondo.
    $disabled-text-color El panel desactivó el color del texto.
    $disabled-descripción-color El panel desactivó el color del texto de descripción de cabecera.
    $body antecedentes $body-color El color del texto del cuerpo del panel.

    Palettes & Colors

    Primero creamos una paleta personalizada que luego puede pasarse a nuestro 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

    Puedes diseñar el panel de expansió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.

    • Usalight-* clases para el tema ligero.
    • Usadark-* clases para el tema oscuro.
    • Añadir el nombre del componente después del prefijo, por ejemplo, ,light-expansion-panel,dark-expansion-panel.

    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 del panel de expansión. La sintaxis es la siguiente:

    <igx-expansion-panel
      class="!light-expansion-panel
      ![--header-background:#4F6A5A]
      ![--body-background:#A3C7B2]"
    >
      ...
    </igx-expansion-panel>
    
    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 panel de expansión debería verse así:

    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>
    ...
    

    Puedes ver los resultados a continuación:

    Multiple panel scenario

    Ver el tema igxAccordion

    API Reference

    Theming Dependencies