Descripción general del componente de tarjeta Angular

    Angular Card representa un contenedor flexible que tiene diferentes elementos como texto de título, descripciones, estilos de imagen, botones de llamada a la acción, enlaces y otros. Para representar un escenario/contenido determinado de la mejor manera posible, ofrece varias opciones de visualización, encabezados, pies de página, así como colores de fondo, animaciones y más.

    Este componente liviano Angular Card se utiliza para crear todo tipo de tarjetas, algunas de ellas pueden ser: tarjetas de presentación, tarjetas con material invertido y tarjetas apiladas.

    Angular Card Example

    A continuación, puede ver una muestra básica de una tarjeta de Ignite UI for Angular bien elaborada con secciones principales de tarjeta como imagen, título, subtítulo, contenido de la tarjeta principal, contenedor para un botón.

    Getting Started with Ignite UI for Angular Card

    Para comenzar con el componente Ignite UI for Angular Card, 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 next step is to import the IgxCardModule inside your app.module.ts file.

    // app.module.ts
    ...
    import { IgxCardModule } from 'igniteui-angular/card';
    // import { IgxCardModule } from '@infragistics/igniteui-angular'; for licensed package
    
    @NgModule({
        ...
        imports: [..., IgxCardModule],
        ...
    })
    export class AppModule {}
    

    Alternativamente,16.0.0 puedes importarlosIgxCardComponent como una dependencia independiente, o usar elIGX_CARD_DIRECTIVES token para importar el componente y todos sus componentes y directivas de soporte.

    // home.component.ts
    
    import { IGX_CARD_DIRECTIVES } from 'igniteui-angular/card';
    // import { IGX_CARD_DIRECTIVES } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-home',
        template: `
        <igx-card>
            <igx-card-media height="196px">
                <img [src]="https://images.unsplash.com/photo-1518235506717-e1ed3306a89b?ixlib=rb-1.2.1&auto=format&fit=crop&w=640&q=50">
            </igx-card-media>
    
            <igx-card-header>
                <h3 igxCardHeaderTitle>New York</h3>
                <h5 igxCardHeaderSubtitle>City in New York</h5>
            </igx-card-header>
    
            <igx-card-content>
                <p>New York City comprises 5 boroughs sitting where the Hudson River meets the Atlantic Ocean. At its core is Manhattan, a densely populated borough that’s among the world’s major commercial, financial and cultural centers.</p>
            </igx-card-content>
    
            <igx-card-actions>
                <button igxButton igxRipple>Read More</button>
                <button igxIconButton="flat" igxRipple igxRippleCentered="true">
                    <igx-icon>favorite</igx-icon>
                </button>
                <button igxIconButton="flat" igxRipple igxRippleCentered="true">
                    <igx-icon>share</igx-icon>
                </button>
            </igx-card-actions>
        </igx-card>
        `,
        styleUrls: ['home.component.scss'],
        standalone: true,
        imports: [IGX_CARD_DIRECTIVES]
        /* or imports: [IgxCardComponent,
            IgxCardHeaderComponent,
            IgxCardMediaDirective,
            IgxCardContentDirective,
            IgxCardActionsComponent,
            IgxCardFooterDirective,
            IgxCardHeaderTitleDirective,
            IgxCardHeaderSubtitleDirective,
            IgxCardThumbnailDirective,
            IgxButtonDirective,
            IgxRippleDirective] */
    })
    export class HomeComponent {}
    

    Now that you have the Ignite UI for Angular Card module or directives imported, you can start using the igx-card component.

    Using the Angular Card Component

    Luego, para representar la plantilla de la tarjeta de demostración, podemos agregar el siguiente código.

    <!--card.component.html>-->
    
    <igx-card>
        <igx-card-media height="196px">
            <img [src]="https://images.unsplash.com/photo-1518235506717-e1ed3306a89b?ixlib=rb-1.2.1&auto=format&fit=crop&w=640&q=50">
        </igx-card-media>
    
        <igx-card-header>
            <h3 igxCardHeaderTitle>New York</h3>
            <h5 igxCardHeaderSubtitle>City in New York</h5>
        </igx-card-header>
    
        <igx-card-content>
            <p>New York City comprises 5 boroughs sitting where the Hudson River meets the Atlantic Ocean. At its core is Manhattan, a densely populated borough that’s among the world’s major commercial, financial and cultural centers.</p>
        </igx-card-content>
    
        <igx-card-actions>
            <button igxButton igxRipple>Read More</button>
            <button igxIconButton="flat" igxRipple igxRippleCentered="true">
                <igx-icon>favorite</igx-icon>
            </button>
            <button igxIconButton="flat" igxRipple igxRippleCentered="true">
                <igx-icon>share</igx-icon>
            </button>
        </igx-card-actions>
    </igx-card>
    

    You will notice a few things above. First when we want to tag an elements as a header title, like the h3 heading, we place it between the igx-card-header tags and attach the igxCardHeaderTitle directive to the element. Conversely, if we wanted to make another heading element a subtitle we would attach the igxCardHeaderSubtitle to it.

    Any image or video we want to show in the Angular Card, we wrap inside the igx-card-media tags. The igx-card-media allows us to size the content placed inside via the width and height attributes. In the example above we provided just height, which would leave the width to auto, thus allowing the image to stretch across the entire card surface, while maintaining the set height.

    You can place anything inside the igx-card-content tags. Usually text goes there.

    Finally, the igx-card-actions is where you'd place any actionable items, like buttons. If you use the igxButton directive on an element, it will automatically be placed correctly according to the material design spec inside the area.

    Media, Thumbs, and Avatars

    If you want to show an image or icon in the card header next to the title and subtitle, you can do it by using the igxCardThumbnail directive.

    Taking the card above as an example, we can edit the contents of the igx-card-header and add a igxCardThumbnail container to hold an icon:

    <igx-card-header>
        <div igxCardThumbnail>
            <igx-icon>place</igx-icon>
        </div>
        
        <h3 igxCardHeaderTitle>Title</h3>
        <h5 igxCardHeaderSubtitle>Subtitle</h5>
    </igx-card-header>
    

    El ejemplo anterior mostrará el ícono junto al título y subtítulo en el encabezado de la tarjeta.

    We also automatically detect the presence of igx-avatar or igx-card-media placed in the card header. They will appear as if they were card thumbnails. So you can do:

    <igx-card-header>
        <igx-avatar>
            <igx-icon>place</igx-icon>
        </igx-avatar>
    
        <h3 igxCardHeaderTitle>Title</h3>
        <h5 igxCardHeaderSubtitle>Subtitle</h5>
    </igx-card-header>
    

    o incluso esto:

    <igx-card-header>
        <igx-card-media width="40px" height="40px">
            <img src="https://images.unsplash.com/photo-1518235506717-e1ed3306a89b?ixlib=rb-1.2.1&auto=format&fit=crop&w=80&q=50">
        </igx-card-media>
    
        <h3 igxCardHeaderTitle>Title</h3>
        <h5 igxCardHeaderSubtitle>Subtitle</h5>
    </igx-card-header>
    

    Outlined cards

    The card has a type attribute you can set to either default (set automatically if omitted), or outlined. The outlined type removes any shadows from the card, replacing them with a thin border to separate the card from the background.

    Angular Card Horizontal Layout

    By default all sections of the card (header, content, media, actions) are laid out vertically. This is nice when we have a lot of vertical space. Say we wanted to lay out all the sections in the card horizontally. We can use the horizontal attribute of the card to set its layout.

    A continuación se muestra un ejemplo de una tarjeta horizontal delineada:

    <igx-card type="outlined" [horizontal]="horizontal">
        <div class="h-sample-column">
            <igx-card-header>
                <h5 igxCardHeaderTitle>{{card.title}}</h5>
                <h5 igxCardHeaderSubtitle>{{card.subtitle}}</h5>
                <igx-card-media width="64px" height="64px">
                    <img [src]="card.imageUrl">
                </igx-card-media>
            </igx-card-header>
    
            <igx-card-content>
                <p>{{card.content}}</p>
            </igx-card-content>
        </div>
    
        <igx-divider [vertical]="horizontal"></igx-divider>
    
        <igx-card-actions layout="justify">
            <button *ngFor="let icon of card.icons;" igxIconButton="flat" igxRipple igxRippleCentered="true">
                <igx-icon>{{icon}}</igx-icon>
            </button>
        </igx-card-actions>
    </igx-card>
    

    We are using the .h-sample-column class to bundle the igx-card-header and igx-card-content together, keeping them aligned vertically, while other sections in the card align horizontally.

    The styles that .h-sample-column class applies are:

    .h-sample-column {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      flex: 1 1 0%;
    
      igx-card-header {
          padding-bottom: 0;
      }
    }
    

    Notice how the buttons in the igx-card-actions have now switched to a vertical layout. The igx-card-actions has an inverse layout relationship with its parent. So whenever the card's horizontal attribute is set to true the actions vertical property will be set to true and vice versa.

    You can set the vertical attribute of he actions area explicitly, thus overriding this default behavior.

    <igx-card-actions layout="justify" [vertical]="false">
        <button *ngFor="let icon of card.icons;" igxIconButton="flat" igxRipple igxRippleCentered="true">
            <igx-icon>{{icon}}</igx-icon>
        </button>
    </igx-card-actions>
    

    Si todo ha ido bien nuestra tarjeta debería quedar así:

    Alternative layouts

    You can get even more creative with the layout of the igx-card.

    Below is an example showing how you can create a semi-horizontal card, where we have every section of the card laid out vertically, while the igx-card-media appears alongside the vertical sections of the card.

    <igx-card [horizontal]="horizontal">
        <div igxLayout igxLayoutDir="column" igxFlex igxFlexGrow="1">
            <igx-card-header>
                <igx-avatar [src]="card.avatarUrl"></igx-avatar>
                <h5 igxCardHeaderTitle>{{card.title}}</h5>
                <h5 igxCardHeaderSubtitle>{{card.subtitle}}</h5>
            </igx-card-header>
    
            <igx-card-content>
                <p>{{card.content}}</p>
            </igx-card-content>
    
            <igx-card-actions [vertical]="false">
                <button *ngFor="let button of card.buttons;" igxButton="flat" igxRipple>
                    {{button}}
                </button>
            </igx-card-actions>
        </div>
    
        <igx-card-media width="96px">
            <img [src]="card.imageUrl">
        </igx-card-media>
    </igx-card>
    

    Angular Card Actions

    El área de acciones Angular Card permite una configuración adicional a lo que ya hemos mencionado.

    You can position elements in the card actions area either in the start or the end by using the igxStart or igxEnd directives.

    <igx-card-actions>
        <button igxIconButton="flat" igxStart>
            <igx-icon>drag_indicator</igx-icon>
        </button>
        <button igxIconButton="flat" igxEnd>
            <igx-icon>favorite</igx-icon>
        </button>
    </igx-card-actions>
    

    You can justify the buttons so that they are laid out across the entire axis, not at the opposite ends. To do that, use the layout attribute and set its value to justify, like below:

    <igx-card-actions layout="justify">
        <button igxButton>Button</button>
    
        <button igxIconButton="flat">
            <igx-icon>star</igx-icon>
        </button>
    </igx-card-actions>
    

    Estilismo

    Card Theme Property Map

    Cambiar la$background propiedad actualiza automáticamente las siguientes propiedades dependientes:

    Propiedad principal Propiedad dependiente Descripción
    $background $header-text-color The text color of the card title.
    $subtitle-text-color The text color of the card subtitle.
    $content-text-color The text color of the card content.
    $actions-text-color The text color of the card buttons.

    To get started with styling the card, 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 card-theme and providing just a few styling parameters. If you only specify the $background parameter, the appropriate foreground colors will be automatically chosen, either black or white, based on which offers better contrast with the background.

    $custom-card-theme: card-theme(
        $background: #011627,
        $subtitle-text-color: #ecaa53,
    );
    

    As seen, the card-theme exposes some useful parameters for basic styling of its items.

    Finalmente, incluya el tema personalizado en su aplicación:

    @include css-vars($custom-card-theme);
    

    In the sample below, you can see how using the card component with customized CSS variables allows you to create a design that visually resembles the card used in the Ant design system.

    Styling with Tailwind

    Puedes decorarloscard 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-card,dark-card.

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

    You can find the full list of properties in the card-theme. The syntax is as follows:

    <igx-card
    class="!light-card
    ![--background:#193625]
    ![--subtitle-text-color:#ECAA53]"
    elevated>
    ...
    </igx-card>
    
    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.

    At the end your card should look like this:

    Summary

    En este artículo cubrimos mucho terreno con el componente de la tarjeta. Primero, creamos una tarjeta muy simple con contenido de texto solamente. Luego agregó algunas imágenes para hacer la tarjeta un poco más atractiva. Utilizamos algunos componentes Ignite UI for Angular adicionales dentro de nuestra tarjeta, avatar, botones e íconos, para enriquecer la experiencia y agregar algunas funcionalidades. Y, por último, cambiamos el tema de la tarjeta estableciendo algunos colores de tema expuestos, creando paletas personalizadas y ampliando los esquemas. El componente de la tarjeta es capaz de mostrar más diseños diferentes que vale la pena explorar en la demostración de la tarjeta al comienzo de este artículo.

    API and Style References

    Para obtener información más detallada sobre la API de la tarjeta, consulte los siguientes enlaces:

    Los siguientes estilos CSS integrados nos ayudaron a lograr este diseño de tarjeta:

    Componentes y/o directivas adicionales que se utilizaron:

    Styles:

    Theming Dependencies

    Additional Resources

    Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.