Angular Descripción general del componente de vista de lista

    The Ignite UI for Angular List component displays rows of items and supports one or more header items as well as search and filtering of list items. Each list item is completely templatable and supports any valid HTML or Angular component. The list component also providers built in panning functionality, templates for empty and loading states, and supports virtualization for large lists using the IgxForOf directive.

    Angular List Example

    The following example represents a list populated with contacts with a name and a phone number properties. The IgxList component uses igx-avatar and igx-icon to enrich the user experience and expose the capabilities of setting avatar picture and different icon for favorite a contact. In addition, the List View expose sorting capabilities achieved by using our filtering pipe.

    Getting Started with Ignite UI for Angular List

    Para comenzar con el componente Vista de lista de Ignite UI for Angular, 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 importar elIgxListModule archivo en el app.module.ts.

    Note

    This component can utilize the HammerModule optionally.It can be imported in the root module of the application in order for touch interactions to work as expected..

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

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

    // home.component.ts
    
    import { HammerModule } from '@angular/platform-browser';
    import { IGX_LIST_DIRECTIVES } from 'igniteui-angular/list';
    // import { IGX_LIST_DIRECTIVES } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-home',
        template: `
        <igx-list>
            <igx-list-item isHeader="true">Header</igx-list-item>
            <igx-list-item>Item 1</igx-list-item>
            <igx-list-item>Item 2</igx-list-item>
            <igx-list-item>Item 3</igx-list-item>
        </igx-list>
        `,
        styleUrls: ['home.component.scss'],
        standalone: true,
        imports: [IGX_LIST_DIRECTIVES, HammerModule]
        /* or imports: [IgxListComponent, IgxListItemComponent, HammerModule] */
    })
    export class HomeComponent {}
    

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

    Using the Angular List

    Then in the template of our contacts component we can create our list, but what if currently (or at some point in the future) we have no items in it? In this case, the Angular list provides us with a default template that is used when the list is empty. We can always provide our own template for the look of our empty list by simply using the igxEmptyList directive. In this case, the default template will not be used:

    <!--contacts.component.html-->
    
    <igx-list>
        <ng-template igxEmptyList>
            <p class="empty">No contacts! :(</p>
        </ng-template>
    </igx-list>
    

    Y nuestro estilo para la plantilla vacía:

    /* contacts.component.css */
    
    .empty {
        color: rgba(0, 153, 255, 1);
        font-size: 25px;
        font-weight: 600;
        text-shadow: 2px 1px 2px rgba(150, 150, 150, 1);
    }
    

    Si todo salió bien, así es como debería verse nuestra lista vacía:

    Sometimes there may be a delay in your data loading. In this case you can set the list's isLoading property to true and a default template will inform the user regarding the ongoing data loading process. You can also provide your own loading template using the igxDataLoading directive:

    <!--contacts.component.html-->
    
    <igx-list>
        <ng-template igxDataLoading>
            <p class="loading">Patience, we are currently loading your data...</p>
        </ng-template>
    </igx-list>
    
    /* contacts.component.css */
    
    .loading {
        color: rgba(255, 153, 0, 1);
        font-size: 25px;
        font-weight: 600;
        text-shadow: 2px 1px 2px rgba(150, 150, 150, 1);
    }
    

    Add List Items

    Es bueno tener una plantilla para cuando la lista esté vacía, ¡pero ahora agreguemos algunos elementos! Podemos agregar el siguiente código para obtener una lista simple de elementos:

    <!--contacts.component.html-->
    
    <igx-list>
        <igx-list-item isHeader="true">Header</igx-list-item>
        <igx-list-item>Item 1</igx-list-item>
        <igx-list-item>Item 2</igx-list-item>
        <igx-list-item>Item 3</igx-list-item>
    </igx-list>
    

    Si todo ha ido bien deberías ver lo siguiente en tu navegador:

    Mejoremos un poco nuestro juego y mejoremos los elementos de nuestra lista. Supongamos que queremos crear una lista Angular de contactos con un nombre y un número de teléfono debajo del nombre. En nuestro archivo typescript de componentes podemos definir una lista de contactos:

    // contacts.component.ts
    ...
    public contacts = [{
        name: "Terrance Orta",
        phone: "770-504-2217"
    }, {
        name: "Richard Mahoney",
        phone: "423-676-2869"
    }, {
        name: "Donna Price",
        phone: "859-496-2817"
    }, {
        name: "Lisa Landers",
        phone: "901-747-3428"
    }, {
        name: "Dorothy H. Spencer",
        phone: "573-394-9254"
    }];
    

    Ahora que tenemos algunos datos que queremos representar, configuremos algunas marcas. Si queremos algo de estilo listo para usar, podemos usar algunas de las directivas que vienen con los elementos de la lista.

    Veamos cómo podemos usar algunos de ellos en el siguiente ejemplo:

    <!--contacts.component.html-->
    
    <igx-list>
      <igx-list-item isHeader="true">
        Contacts
      </igx-list-item>
      <igx-list-item *ngFor="let contact of contacts">
        <h4 igxListLineTitle>{{ contact.name }}</h4>
        <p igxListLineSubTitle>{{ contact.phone }}</p>
      </igx-list-item>
    </igx-list>
    

    Both directives igxListLineTitle and igxListLineSubTitle gives our list items some default look.

    Después de todo eso, nuestra lista de Angular ahora debería verse así:

    Adding Avatar and Icons

    We can use some of our other components in conjunction with the IgxList component to enrich the experience and add some functionality. We can have a nice picture avatar to the left of the name and phone values. Additionally, we can add a star icon to the right of them to allow the user to favorite a contact. To do that let's grab the IgxAvatar and IgxIcon modules and import them in our app.module.ts file.

    // app.module.ts
    
    ...
    import { IgxListModule } from 'igniteui-angular/list';
    import { IgxAvatarModule } from 'igniteui-angular/avatar';
    import { IgxIconModule } from 'igniteui-angular/icon';
    // import { IgxListModule, IgxAvatarModule, IgxIconModule } from '@infragistics/igniteui-angular'; for licensed package
    
    @NgModule({
        ...
        imports: [..., IgxAvatarModule, IgxIconModule],
    })
    export class AppModule {}
    

    Next, we need to add some more information to our contact object, like a photo source for our avatar and a isFavorite property to indicate the contact's favorite status.

    // contacts.component.ts
    
    public contacts = [{
        name: 'Terrance Orta',
        phone: '770-504-2217',
        photo: 'https://randomuser.me/api/portraits/men/27.jpg',
        isFavorite: false
    }, {
        name: 'Richard Mahoney',
        phone: '423-676-2869',
        photo: 'https://randomuser.me/api/portraits/men/1.jpg',
        isFavorite: true
    }, {
        name: 'Donna Price',
        phone: '859-496-2817',
        photo: 'https://randomuser.me/api/portraits/women/50.jpg',
        isFavorite: false
    }, {
        name: 'Lisa Landers',
        phone: '901-747-3428',
        photo: 'https://randomuser.me/api/portraits/women/3.jpg',
        isFavorite: false
    }, {
        name: 'Dorothy H. Spencer',
        phone: '573-394-9254',
        photo: 'https://randomuser.me/api/portraits/women/67.jpg',
        isFavorite: true
    }];
    

    Genial, ahora actualicemos la plantilla de nuestra lista de contactos para mostrar el avatar y el ícono. Nuevamente podemos hacerlo usando algunas de las directivas de lista.

    <!--contacts.component.html-->
    
    <igx-list>
      <igx-list-item isHeader="true">
        Contacts
      </igx-list-item>
      <igx-list-item #item *ngFor="let contact of contacts;">
          <igx-avatar igxListThumbnail [src]="contact.photo" shape="circle"></igx-avatar>
          <h4 igxListLineTitle>{{ contact.name }}</h4>
          <p igxListLineSubTitle class="phone">{{ contact.phone }}</p>
          <span igxListLine>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dicta, laborum.</span>
          <igx-icon igxListAction [color]="contact.isFavorite ? 'orange' : 'lightgray'" (click)="toggleFavorite(item)">star</igx-icon>
      </igx-list-item>
    </igx-list>
    
    • igxListThumbnail is meant to be used if we need to add some kind of media at the beginning of our list items. The directive will wrap the target element in our case igx-avatar in a container that will provide some default position and spacing.
    • igxListAction is meant to be used for list items that have some kind of action or metadata, for example, switch, radio-button, checkbox, etc. In our case the action is will be represented by an igx-icon. Again, the directive will wrap the target element in a container that will have the correct position and spacing.
    • igxListLine is meant to be used if we need some text in-between igxListThumbnail and igxListAction the directive will make sure that the text position, spacing and alignment will look great with the other two directives around.

    A continuación, escuchamos un evento de clic en el componente IgxIcon para alternar la propiedad isFavorite en nuestro objeto de contacto.

    // contacts.component.ts
    
    ...
    toggleFavorite(item: IgxListItem) {
        const contact = this.contacts[item.index - 1];
        contact.isFavorite = !contact.isFavorite;
    }
    

    Let's also allow the user to choose the size of the list by using the --ig-size CSS custom property. We will do this by importing the IgxButtonGroupModule and using the IgxButtonGroup to display all size values. This way whenever one gets selected, we will update the size of the list.

    // app.module.ts
    ...
    import { IgxButtonGroupModule } from 'igniteui-angular/button-group';
    // import { IgxButtonGroupModule } from '@infragistics/igniteui-angular'; for licensed package
    
    @NgModule({
        imports: [..., IgxButtonGroupModule]
    })
    
    <!--contacts.component.html-->
    
    <igx-buttongroup [values]="sizes" (selected)="selectSize($event)"></igx-buttongroup>
    ...
    <igx-list>
        ...
    </igx-list>
    
    // contacts.component.ts
    
    public size = 'large';
    public sizes;
    
    public ngOnInit() {
        this.sizes = [
            { label: 'large', selected: this.size === 'large', togglable: true },
            { label: 'medium', selected: this.size === 'medium', togglable: true },
            { label: 'small', selected: this.size === 'small', togglable: true }
        ];
    }
    
    public selectSize(event: any) {
        this.size = this.sizes[event.index].label;
    }
    
    
    @HostBinding('style.--ig-size')
    protected get sizeStyle() {
        return `var(--ig-size-${this.size})`;
    }
    

    Y aquí está el resultado de todo ese trabajo:

    List Items Panning

    Now that we have such a beautiful Angular list with contacts and their phone numbers, why don't we implement an ability to call a contact. The IgxList has the perfect solution for this - list item panning. To do this you have to implement the following steps:

    • Enable the panning using the allowLeftPanning and/or the allowRightPanning properties
    • Definir plantillas para la panorámica izquierda y/o derecha
    • Manejar los eventos de panorámica del elemento de la lista y realizar la acción deseada

    The following example demonstrates how to handle both left and right panning. The event handler for right panning shows a toast message. The event handler for the left panning deletes an item from the IgxList.

    Note

    Please note that the list item removal is an application task. The IgxList itself cannot remove items from the data source because the IgxList does not have reference to the data source.

    Aquí está el código HTML del ejemplo:

    <!-- contacts.component.html -->
    
    <igx-list [allowLeftPanning]="true" [allowRightPanning]="true"
      (leftPan)="leftPanPerformed($event)" (rightPan)="rightPanPerformed($event)">
      <ng-template igxListItemLeftPanning>
        <div class="listItemLeftPanningStyle">
          <igx-icon [color]="white" style="margin-left:10px">delete</igx-icon>Delete
        </div>
      </ng-template>
      <ng-template igxListItemRightPanning>
        <div class="listItemRightPanningStyle">
          <igx-icon [color]="white" style="margin-right:10px">call</igx-icon>Dial
        </div>
      </ng-template>
      <igx-list-item isHeader="true">Contacts</igx-list-item>
      <igx-list-item #item *ngFor="let contact of contacts">
        <igx-avatar igxListThumbnail [src]="contact.photo" shape="circle"></igx-avatar>
        <h4 igxListLineTitle>{{ contact.name }}</h4>
        <p igxListLineSubTitle class="phone">{{ contact.phone }}</p>
        <igx-icon igxListAction [color]="contact.isFavorite ? 'orange' : 'lightgray'" (click)="toggleFavorite(item)">star</igx-icon>
      </igx-list-item>
    </igx-list>
    
    <igx-toast #toast></igx-toast>
    

    El ejemplo anterior utiliza algunos estilos CSS que se pueden encontrar aquí:

    /* contacts.component.css */
    
    igx-icon {
        cursor: pointer;
        user-select: none;
    }
    
    .listItemLeftPanningStyle {
        display: flex;
        flex-direction: row-reverse;
        background-color:orange;
        color: white;
        width: 100%;
        padding-right: 10px;
        align-items: center;
    }
    
    .listItemRightPanningStyle {
        display: flex;
        flex-direction: row;
        background-color:limegreen;
        color: white;
        width: 100%;
        padding-left: 10px;
        align-items: center;
    }
    

    Y finalmente aquí está el código mecanografiado que maneja los eventos de panorámica:

    // contacts.component.ts
    
    ...
    @ViewChild('toast')
    public toast: IgxToastComponent;
    
    public rightPanPerformed(args) {
      args.keepItem = true;
      this.toast.message = 'Dialing ' + this.contacts[args.item.index - 1].name;
      this.toast.open();
    }
    
    public leftPanPerformed(args) {
      args.keepItem = false;
      setTimeout((idx = args.item.index - 1) => {
        this.toast.message = 'Contact ' + this.contacts[idx].name + ' removed.';
        this.toast.open();
        this.contacts.splice(idx, 1);
      }, 500);
    }
    
    ...
    
    Note

    When panning list items there is a threshold which must be reached in order for the panning events to be emitted. You can change the threshold using the IgxList's panEndTriggeringThreshold property. By default this property has a value of 0.5 which means 50% of list item's width.

    Ahora intente desplazarse por los elementos de la lista usted mismo:

    Angular filter list

    Nuestra lista se ve bien, pero ¿no sería aún mejor si pudiéramos buscar contactos por nombre? Esto lo podemos lograr fácilmente utilizando nuestro tubo filtrante. Hagámoslo.

    Agreguemos primero un campo de entrada a la parte superior de nuestra plantilla de componente Angular y vinculémoslo a una propiedad de nuestro componente llamada searchContact:

    <!--contacts.component.html-->
    
    <igx-input-group type="search" class="search">
        <igx-prefix>
            <igx-icon>search</igx-icon>
        </igx-prefix>
        <input #search igxInput placeholder="Search Contacts" [(ngModel)]="searchContact">
        <igx-suffix *ngIf="search.value.length > 0" (click)="searchContact = null">
            <igx-icon>clear</igx-icon>
        </igx-suffix>
    </igx-input-group>
    

    It's time to import the IgxFilterModule and the IgxInputGroupModule in our app.module.ts file and IgxFilterOptions in our contacts component:

    // app.module.ts
    ...
    import { IgxFilterModule } from 'igniteui-angular/directives';
    import { IgxInputGroupModule } from 'igniteui-angular/input-group';
    // import { IgxFilterModule, IgxInputGroupModule } from '@infragistics/igniteui-angular'; for licensed package
    
    @NgModule({
        imports: [..., IgxFilterModule, IgxInputGroupModule]
    })
    
    // contacts.component.ts
    ...
    import { IgxFilterOptions } from 'igniteui-angular/directives';
    // import { IgxFilterOptions } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({...})
    export class ContactListComponent {
        public searchContact: string;
        ...
        get filterContacts(): IgxFilterOptions {
            const fo = new IgxFilterOptions();
            fo.key = 'name';
            fo.inputValue = this.searchContact;
            return fo;
        }
    }
    

    After importing the IgxFilterOptions, we need to register a new getter method that will return the filtering options to be used by the pipe each time the searchContact property gets updated. For the filter to work we need to register a key to filter the contact object by. In our case that would be the name of each contact. The second property that has to be registered on the IgxFilterOptions object is the value that we should check against when comparing our contact name. This would be the searchContact property that we bound to the input field above our contacts list.

    Finalmente, debemos aplicar el tubo de filtrado a los datos de nuestros contactos antes de poder usarlo. Entonces en nuestra plantilla simplemente agregamos:

    <!--contacts.component.html-->
    
    <igx-list-item *ngFor="let contact of contacts | igxFilter: filterContacts; let i = index">
        ...
    </igx-list-item>
    

    List Item Selection

    The list items have a selected property that helps us track which items are "selected". This property allows us to identify and manage the selection status of each item.

    Here's an example illustrating how the visual style of the items changes when using the selected property:

    By default, the selected property is set to false. We can toggle its value using an inline expression bound to the (click) event on each list item, effectively switching the visual state of the item each time it's clicked.

    <igx-list>
        <igx-list-item [isHeader]="true">Contacts</igx-list-item>
        @for (contact of contacts | igxFilter: filterContacts; track contact) {
          <igx-list-item [selected]="contact.selected" (click)="contact.selected = !contact.selected">
            <igx-avatar igxListThumbnail [src]="contact.photo" shape="circle"></igx-avatar>
            <span igxListLineTitle>{{ contact.name }}</span>
            <span igxListLineSubTitle>{{ contact.phone }}</span>
            <igx-icon igxListAction [style.color]="contact.isFavorite ? 'orange' : 'lightgray'" igxRipple="pink"
              [igxRippleCentered]="true" (click)="toggleFavorite(contact, $event)"
            (mousedown)="mousedown($event)">star</igx-icon>
          </igx-list-item>
        }
      </igx-list>
    

    El elemento de la lista también expone algunas variables CSS que puede usar para diseñar diferentes partes de los elementos seleccionados:

    • --item-background-selected
    • --item-text-color-selected
    • --item-title-color-selected
    • --item-action-color-selected
    • --item-subtitle-color-selected
    • --item-thumbnail-color-selected
    igx-list-item {
      --item-background-selected: var(--ig-secondary-500);
      --item-title-color-selected: var(--ig-secondary-500-contrast);
      --item-subtitle-color-selected: var(--ig-info-100);
    }
    

    If you prefer to use the list theming function, there are parameters available that allow you to style the selected state of the list items. You can find more information about these parameters here: list-theme

    Chat Component

    En el ejemplo siguiente se muestra cómo crear un componente de chat simple mediante IgxList.

    Estilismo

    List 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 $header-antecedentes El color de fondo de la cabecera de la lista.
    $item antecedentes El color de fondo del elemento de la lista.
    $header-antecedentes $header-text-color El color del texto de la cabecera de la lista.
    $item antecedentes
    $background El color de fondo de la lista.
    $header-antecedentes El color de fondo de la cabecera de la lista.
    $item-plano-flotar El elemento de la lista pasa el cursor al color de fondo.
    $item-text-color El color del texto de los elementos de la lista.
    $item-título-color El color del título del elemento de la lista.
    $item-acción-color El color de acción del elemento de la lista.
    $item-miniatura-color El color de miniatura del ítem de la lista.
    $item-subtítulos-color El color de subtítulos del elemento de la lista.
    $border color El color del borde de la lista. (Solo fluido/Bootstrap)
    $item-plano-flotar
    $item-activo-fondo El color de fondo del elemento de la lista activa.
    $item-text-color-hover El elemento de la lista pasa el color del texto.
    $item-título-color-pasar el cursor El elemento de la lista pasa el cursor al color del título.
    $item-acción-color-flotar El elemento de la lista flota en color de acción.
    $item-miniatura-color-pasar el cursor El elemento de la lista pasa el cursor al color de la miniatura.
    $item-subtítulo-color-pasar el cursor El elemento de la lista pasa el cursor al color de los subtítulos.
    $item-activo-fondo
    $item-trasfondo seleccionado El color de fondo del elemento seleccionado de la lista.
    $item-color-text-active El color del texto del elemento de la lista activa.
    $item-título-color-activo El color del título del ítem de la lista activa.
    $item-acción-color-activo El color de acción del ítem de la lista activa.
    $item-color-miniatura-activo El color de miniatura del elemento de la lista activa.
    $item-subtítulo-color-activo El color de subtítulos del elemento de la lista activa.
    $item-trasfondo seleccionado
    $item-text-color-selected El color del texto del elemento seleccionado.
    $item-título-color-seleccionado El color del título del elemento seleccionado de la lista.
    $item-acción-color-seleccionado El color de acción del elemento seleccionado de la lista.
    $item-miniatura-color-seleccionado El color de miniatura del elemento seleccionado de la lista.
    $item-subtítulo-color-seleccionado El elemento seleccionado de la lista de subtítulos, color.

    Nota: Los resultados reales pueden variar según la variante del tema.

    Veamos cómo podemos cambiar el fondo de nuestra lista. Primero necesitamos importar index.scss al archivo .scss de nuestro componente.

    @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 list-theme and by passing only the $background parameter, the theme will automatically calculate the state colors and appropriate contrasting foregrounds. However, you can still manually define them if desired.

    $my-list-theme: list-theme(
      $background: #57a5cd
    );
    

    Take a look at the list-theme section for a complete list of available parameters for styling the list.

    El último paso es incluir los temas recién creados.

    @include css-vars($my-list-theme);
    

    El resultado es el siguiente:

    Para obtener una lista completa de los parámetros que puede cambiar para el componente de lista, consulte: Estilos de componentes IgxList

    Styling with Tailwind

    Puedes personalizar la lista 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-list,dark-list.

    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 lista. La sintaxis es la siguiente:

    <igx-list class="!light-list ![--background:#81B698] ![--item-background:#A3C7B2]">
        ...
    </igx-list>
    
    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 lista debería ser así:

    API References

    En este artículo cubrimos mucho terreno con el componente de lista de Angular. Creamos una lista de elementos de contacto. Usamos algunos componentes de Ignite UI for Angular adicionales dentro de los elementos de nuestra lista, como avatares e íconos. Creé un diseño de artículo personalizado y le di estilo. Finalmente, agregamos el filtrado de listas. El componente de lista tiene algunas API más para explorar, que se enumeran a continuación.

    Componentes Angular adicionales que se utilizaron:

    Theming Dependencies

    Additional Resources

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