Visão geral do componente Angular List View

    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 começar a usar o componente Ignite UI for Angular List View, 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 oIgxListModule arquivo no 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 você pode importarIgxListComponent como uma dependência independente ou usar oIGX_LIST_DIRECTIVES token para importar o componente e todos os seus componentes e diretivas de suporte.

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

    E nosso estilo para o modelo vazio:

    /* 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);
    }
    

    Se tudo correr bem, é assim que nossa lista vazia deve ficar:

    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

    É legal ter um modelo para quando a lista estiver vazia, mas agora vamos adicionar alguns itens! Podemos adicionar o seguinte código para obter uma lista simples de itens:

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

    Se tudo correr bem, você deverá ver o seguinte no seu navegador:

    Vamos melhorar um pouco o nosso jogo e aprimorar os itens da nossa lista. Digamos que queremos criar uma lista Angular de contatos com um nome e um número de telefone exibidos abaixo do nome. Em nosso arquivo typescript do componente, podemos definir uma lista de contatos:

    // 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"
    }];
    

    Agora que temos alguns dados que queremos renderizar, vamos configurar alguma marcação. Se quisermos algum estilo pronto para uso, podemos usar algumas das diretivas que vêm com os itens da lista.

    Vejamos como podemos usar alguns deles no próximo exemplo:

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

    Depois de tudo isso, nossa lista Angular deve ficar assim:

    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
    }];
    

    Legal, agora vamos atualizar o template para nossa lista de contatos para mostrar o avatar e o ícone. Novamente, podemos fazer isso usando algumas das diretivas 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.

    Em seguida, ouvimos um evento de clique no componente IgxIcon para alternar a propriedade isFavorite em nosso objeto de contato.

    // 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})`;
    }
    

    E aqui está o resultado de todo esse trabalho:

    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 modelo(s) para a panorâmica esquerda e/ou direita
    • Manipule os eventos de panorâmica do item da lista e execute a ação desejada

    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.

    Aqui está o código HTML do exemplo:

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

    O exemplo acima usa alguns estilos CSS que podem ser encontrados aqui:

    /* 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;
    }
    

    E finalmente aqui está o código typescript que manipula os 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.

    Agora tente você mesmo analisar os itens da lista:

    Angular filter list

    Nossa lista está ótima, mas não seria ainda melhor se pudéssemos procurar contatos por nome? Podemos fazer isso facilmente usando nosso pipe de filtragem. Vamos fazer isso.

    Vamos primeiro adicionar um campo de entrada no topo do nosso modelo de componente Angular e vinculá-lo a uma propriedade em nosso componente chamada 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.

    Por fim, precisamos aplicar o pipe de filtragem aos nossos dados de contatos antes de podermos usá-lo. Então, em nosso modelo, simplesmente adicionamos:

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

    O item de lista também expõe algumas variáveis CSS que você pode usar para estilizar diferentes partes dos elementos selecionados:

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

    O exemplo a seguir demonstra como criar um componente de bate-papo simples usando IgxList.

    Estilização

    List Theme Property Map

    Quando você modifica uma propriedade primária, todas as propriedades dependentes relacionadas são atualizadas automaticamente para refletir a alteração:

    Propriedade primária Propriedade dependente Descrição
    $background $header-contexto A cor de fundo do cabeçalho da lista.
    $item-contexto A cor de fundo do item da lista.
    $header-contexto $header-cor-texto A cor do cabeçalho da lista.
    $item-contexto
    $background A cor de fundo da lista.
    $header-contexto A cor de fundo do cabeçalho da lista.
    $item-fundo-pairar O item da lista passe a cor de fundo.
    $item-text-color O item da lista cor do texto.
    $item-título-cor A cor do título do item da lista.
    $item-ação-cor A cor da ação do item da lista.
    $item-cor do thumbnail A cor da miniatura do item da lista.
    $item-legenda-cor O item da lista é a cor das legendas.
    $border cor A cor da borda da lista. (Apenas fluente/Bootstrap)
    $item-fundo-pairar
    $item-ativo-antecedentes A cor de fundo do item da lista ativa.
    $item-text-color-hover O item da lista passa a cor do texto.
    $item-título-cor-passar o mouse O item da lista passa a cor do título.
    $item-ação-cor-pairar O item da lista passa a cor da ação.
    $item-thumbnail-color-hover O item da lista passa a cor da miniatura.
    $item-legenda-cor-passar o mouse O item da lista passe a cor das legendas.
    $item-ativo-antecedentes
    $item-antecedentes selecionados A cor de fundo do item selecionado da lista.
    $item-text-color-active A cor do texto do item da lista ativa.
    $item-título-cor-ativo Cor do título do item da lista ativa.
    $item-ação-cor-ativo A cor de ação do item da lista ativa.
    $item-thumbnail-color-active A miniatura do item da lista de ativos.
    $item-legenda-cor-ativo A cor do item da lista ativa e da legenda.
    $item-antecedentes selecionados
    $item-texto-color-selecionado A cor do texto do item selecionado da lista.
    $item-título-cor-selecionado A cor do título do item selecionado da lista.
    $item-ação-cor-selecionada A cor da ação do item selecionado da lista.
    $item-thumbnail-color-selected A miniatura do item selecionado da lista.
    $item-legenda-cor-selecionada A cor do legenda do item selecionado.

    Nota: Os resultados reais podem variar dependendo da variante do tema.

    Vamos ver como podemos mudar o fundo da nossa lista. Primeiro precisamos importar index.scss para o nosso arquivo .scss do 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.

    A última etapa é incluir os temas recém-criados.

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

    O resultado é o seguinte:

    Para uma lista completa de parâmetros que você pode alterar para o componente de lista, consulte: Estilos IgxListComponent

    Styling with Tailwind

    Você pode estilizar a lista usando nossas classes utilitárias personalizadas do 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.

    • Uselight-* as aulas para o tema da luz.
    • Usedark-* classes para o tema sombrio.
    • Adicione o nome do componente após o prefixo, por exemplo,light-list,dark-list.

    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 da lista. A sintaxe é a seguinte:

    <igx-list class="!light-list ![--background:#81B698] ![--item-background:#A3C7B2]">
        ...
    </igx-list>
    
    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, sua lista deve ficar assim:

    API References

    Neste artigo, cobrimos muito terreno com o componente de lista Angular. Criamos uma lista de itens de contato. Usamos alguns componentes adicionais Ignite UI for Angular dentro dos nossos itens de lista, como avatares e ícones. Criamos alguns layouts de itens personalizados e os estilizamos. Por fim, adicionamos filtragem de lista. O componente de lista tem mais algumas APIs para explorar, que estão listadas abaixo.

    Componentes Angular adicionais que foram usados:

    Theming Dependencies

    Additional Resources

    Nossa comunidade é ativa e sempre acolhedora para novas ideias.