Visão geral do componente Angular Drop Down

    O Ignite UI for Angular Drop Down é um componente que exibe uma lista alternável de valores predefinidos e permite que os usuários selecionem facilmente um único item de opção com um clique. Ele pode ser configurado rapidamente para atuar como um menu suspenso ou você pode simplesmente usá-lo para fornecer informações visuais mais úteis agrupando dados. Com o agrupamento, você pode usar dados planos e hierárquicos. O componente Drop Down permite vinculação declarativa, o que torna possível incorporar conteúdo e links adicionais. Isso também deixa espaço para mais personalização da IU e estilo da aparência da lista suspensa Angular. Além disso, ele é repleto de recursos importantes, como navegação suspensa por teclado e virtualização.

    Angular Drop Down Example

    Este exemplo de drop down Angular demonstra as funcionalidades básicas de uma lista drop down. Clique nele para expandir as opções predefinidas, selecione um item e feche o drop down.

    Getting Started with Ignite UI for Angular Drop Down

    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 issoIgxDropDownModule no seu arquivo app.module.ts.

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

    Alternativamente,16.0.0 você pode importarIgxDropDownComponent como uma dependência independente ou usar oIGX_DROP_DOWN_DIRECTIVES token para importar o componente e todos os seus componentes e diretivas de suporte.

    // home.component.ts
    
    import { NgFor } from '@angular/common';
    import { IGX_DROP_DOWN_DIRECTIVES } from 'igniteui-angular/drop-down';
    import { IgxToggleActionDirective } from 'igniteui-angular/directives';
    import { IgxButtonDirective } from 'igniteui-angular/directives';
    // import { IGX_DROP_DOWN_DIRECTIVES, IgxToggleActionDirective, IgxButtonDirective } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
      selector: 'app-home',
      template: `
        <button
          igxButton="contained"
          [igxToggleAction]="dropdown"
          [igxDropDownItemNavigation]="dropdown"
        >
          Options
        </button>
        <igx-drop-down #dropdown>
          <igx-drop-down-item *ngFor="let item of items">
            {{ item.field }}
          </igx-drop-down-item>
        </igx-drop-down>
      `,
      styleUrls: ['home.component.scss'],
      standalone: true,
      imports: [ IGX_DROP_DOWN_DIRECTIVES, IgxToggleActionDirective, IgxButtonDirective, NgFor ],
      /* or imports: [IgxDropDownComponent, IgxDropDownItemComponent, IgxToggleActionDirective, IgxButtonDirective, NgFor] */
    })
    export class HomeComponent {}
    

    Now that you have the Ignite UI for Angular Drop Down module or directives imported, you can start using the igx-drop-down component.

    Using the Angular Drop Down

    Add Drop Down

    Vamos criar um drop-down simples que fornece vários itens de opção para escolher. Para conseguir isso, usaremos o IgxDropDownComponent, bem como o IgxToggleAction para abrir/fechar o drop-down.

    <!-- dropdown.component.html -->
    <button igxButton="contained" [igxToggleAction]="dropdown" [igxDropDownItemNavigation]="dropdown">
      Options
    </button>
    <igx-drop-down #dropdown>
      <igx-drop-down-item *ngFor="let item of items">
        {{ item.field }}
      </igx-drop-down-item>
    </igx-drop-down>
    
    // dropdown.component.ts
    @Component({...})
    export class MyDropDownComponent {
        public items: Array<{ field: string }> = [
            { field: 'Option 1' },
            { field: 'Option 2' },
            { field: 'Option 3' }
        ];
    }
    

    More Angular Drop Down Examples

    A demonstração padrão mostra o uso de uma Drop Down List alternável no Angular que permite que os usuários finais expandam todos os itens predefinidos e optem por um deles. Confira o exemplo a seguir e veja a Drop Down List Angular em ação.

    Predefined selected item

    Digamos que queremos ter um item selecionado predefinido. Uma maneira de fazer isso é manipulando o evento de abertura do componente drop-down.

    <!-- dropdown.component.html -->
    <button igxButton="contained" [igxToggleAction]="dropdown" [igxDropDownItemNavigation]="dropdown">
      Options
    </button>
    <igx-drop-down #dropdown (opening)="dropdown.setSelectedItem(0)">
      <igx-drop-down-item *ngFor="let item of items">
        {{ item.field }}
      </igx-drop-down-item>
    </igx-drop-down>
    
    // dropdown.component.ts
    export class MyDropDownComponent {
      public items: Array<{ field: string }> = [
        { field: 'Option 1' },
        { field: 'Option 2' },
        { field: 'Option 3' },
      ];
    }
    

    Grouping items

    To provide a more useful visual information, use the isHeader property to group items semantically or the disabled property to display an item as a non-interactive. You can also set the selected property on a particular item to make it the selected item. The igx-drop-down items have out-of-the-box support for igxPrefix, igxSuffix, and igx-divider directives that can contain or be set on HTML elements or other web components.

    <!-- dropdown.component.html -->
    <button igxButton="contained" [igxToggleAction]="dropdown" [igxDropDownItemNavigation]="dropdown">
      Countries
    </button>
    <igx-drop-down #dropdown [width]="'240px'">
      <div class="drop-down__scroll-container">
        <igx-drop-down-item *ngFor="let item of items" [disabled]="item.disabled" [isHeader]="item.header" [selected]="item.selected">
          <igx-icon igxPrefix>place</igx-icon>
          {{ item.field }}
          <span igxSuffix>{{ item.code }}</span>
          <igx-divider></igx-divider>
        </igx-drop-down-item>
      </div>
    </igx-drop-down>
    
    // dropdown.component.ts
    export class MyDropDownComponent {
      public items: any[] = [
        { field: 'European Union', code: 'EU', header: true },
        { field: 'Germany', code: 'DE' },
        { field: 'Bulgaria', code: 'BG', selected: true },
        { field: 'France', code: 'FR', disabled: true },
        { field: 'North America', code: 'NA', header: true },
        { field: 'Canada', code: 'CA' },
        { field: 'United States', code: 'US' },
        { field: 'Mexico', code: 'MX' },
      ];
    }
    

    Se o exemplo estiver configurado corretamente, uma lista de países deverá ser exibida como um grupo sob o cabeçalho União Europeia, França como um item não interativo e Bulgária como um item selecionado:

    Grouping hierarchical data

    The igx-drop-down items can also be grouped using the igx-drop-down-item-group container, making it easier for users to differentiate separate categories. The igx-drop-down-item-group accepts igx-drop-down-item elements as its content and renders them in a grouped fashion.

    // dropdown.component.ts
    export class MyCustomDropDownComponent {
        ...
        public foods: {
            name: string,
            entries: { name: string, refNo: string }[]
        }[] = [
        {
            name: 'Vegetables',
            entries: [{
                name: 'Cucumber',
                refNo: '00000'
            }, {
                name: 'Lettuce',
                refNo: '00001'
            },
            ...]
        }, {
            name: 'Fruits',
            entries: [{
                name: 'Banana',
                refNo: '10000'
            }, {
                name: 'Tomato',
                refNo: '10001'
            },
            ...]
        }, {
            name: 'Meats',
            entries: [{
                name: 'Chicken',
                refNo: '20000'
            }, {
                name: 'Beef',
                refNo: '20001'
            },
            ...]
        }];
    }
    
    <igx-drop-down>
      <igx-drop-down-item-group *ngFor="let foodGroup of foods" [label]="foodGroup.name">
        <igx-drop-down-item *ngFor="let food of foodGroup.entries" [value]="food.refNo">
          {{ food.name }}
        </igx-drop-down-item>
      </igx-drop-down-item-group>
    </igx-drop-down>
    

    The group also has the additional functionality of disabling items inside of its body. For example, lets say we do not want the Meats food group to be selectable in our drop-down. Instead of disabling all of the entries in Meats separately, we can disable the group, as well as all of the child items inside:

    <igx-drop-down>
      <igx-drop-down-item-group *ngFor="let foodGroup of foods" [label]="foodGroup.name" [disabled]="foodGroup.name === 'Meats'">
        <igx-drop-down-item *ngFor="let food of foodGroup.entries" [value]="food.refNo">
          {{ food.name }}
        </igx-drop-down-item>
      </igx-drop-down-item-group>
    </igx-drop-down>
    

    Você pode ver os resultados no exemplo abaixo:

    Você pode configurar o menu suspenso para se comportar como um menu. Para fazer isso, defina o membro cancel da interface ISelectionEventArgs como true no manipulador de eventos selectionChanging. Dessa forma, o item selecionado não é preservado ao abrir o menu e as seleções anteriores são invalidadas. Ainda assim, você pode obter o item clicado por meio do valor do membro newSelection no evento.

    <!-- dropdown.component.html -->
    <div>
      <igx-navbar title="Contacts">
        <button
          [igxToggleAction]="menu"
          [igxToggleOutlet]="outlet"
          [overlaySettings]="overlaySettings"
          [igxDropDownItemNavigation]="menu"
          igxIconButton="flat"
        >
          <igx-icon fontSet="material">more_vert</igx-icon>
        </button>
        <igx-drop-down #menu (selectionChanging)="selectionHandler($event)">
          <igx-drop-down-item *ngFor="let item of items" [value]="item.text">
            <div>{{ item.text }}</div>
          </igx-drop-down-item>
        </igx-drop-down>
      </igx-navbar>
    
      <div>
        <ng-container *ngIf="text">
          <label igxLabel>{{ text }}</label>
        </ng-container>
      </div>
    
      <div igxOverlayOutlet #outlet="overlay-outlet"></div>
    </div>
    
    // dropdown.component.ts
    export class MyMenuComponent {
      public items: Array<{ text: string }> = [
        { text: "Add New Contact" },
        { text: "Edit Contact" },
        { text: "Refresh" },
        { text: "Help" },
      ];
      public text: string;
      public overlaySettings = {
        positionStrategy: new ConnectedPositioningStrategy({
          horizontalDirection: HorizontalAlignment.Left,
          horizontalStartPoint: HorizontalAlignment.Right,
          verticalStartPoint: VerticalAlignment.Bottom,
        }),
        scrollStrategy: new NoOpScrollStrategy(),
      };
    
      public selectionHandler(eventArgs: ISelectionEventArgs) {
        this.text = eventArgs.newSelection.value;
        eventArgs.cancel = true;
      }
    }
    

    Multi-Level Drop Down menu

    O exemplo a seguir demonstra como implementar um menu suspenso de vários níveis que permite ao usuário navegar de forma rápida e fácil por uma hierarquia de conteúdo passando o mouse sobre uma série de menus aninhados.

    For the implementation of the multi-level drop down menu we will use the IgxDropDownComponent as well as a custom directive and service described below.

    In order to configure the IgxDropDownItem to open an additional drop down, add the multiLevel directive that would handle the overlay settings of the nested drop down and manages its opened/closed state through its innerDropdown property.

    <igx-drop-down #dropdown1>
      <igx-drop-down-item [value]="'Web'" multiLevel [innerDropdown]="web">
        Web <igx-icon igxSuffix>chevron_right</igx-icon>
      </igx-drop-down-item>
      ...
    </igx-drop-down>
    
    <igx-drop-down #web>
      <igx-drop-down-item [value]="'App Builder'"> App Builder </igx-drop-down-item>
      ...
    </igx-drop-down>
    

    To configure the multi-level drop down to behave as a menu, you need to handle the selectionChanging event of all drop downs in the hierarchy and cancel the default behavior. Then, in order to handle the selection properly you could use the MultiLevelService's handleSelection method and in order to prevent closing the drop down when clicking on a menu item, use the MultiLevelService's handleClosing methods.

    @ViewChildren(IgxDropDownComponent, { read: IgxDropDownComponent })
    private _dropdowns: QueryList<IgxDropDownComponent>;
    
    @ViewChild('dropdown1', { read: IgxDropDownComponent })
    private _multiLevelDropdown: IgxDropDownComponent;
    
    constructor(private _multiLevelService: MultiLevelService) { }
    
    public ngAfterViewInit(): void {
        this._dropdowns.forEach((dropdown) => {
            dropdown.selectionChanging.subscribe((args) => {
                args.cancel = true;
                const value = args.newSelection.value;
                const categories = this._multiLevelService.categories;
    
                if (categories.includes(value)) {
                    this.selection = '';
                    return;
                }
    
                if (this._multiLevelService.isMultiLevel(dropdown)) {
                    this._multiLevelService.handleSelection();
                } else {
                    dropdown.close();
                }
    
                this.selection = value;
            });
        });
    
        this._multiLevelDropdown.closing.subscribe((args) => {
            this._multiLevelService.handleClosing(args);
        });
    }
    

    O resultado das configurações acima pode ser visto no exemplo abaixo.

    Note

    Para exibir o componente Dropdown aberto inicialmente, é recomendado definir o método open como um retorno de chamada do método requestAnimationFrame. Isso garantirá que a árvore DOM seja repintada e que todos os elementos sejam posicionados corretamente.

    Use the igxDropDownItemNavigation directive to enable keyboard navigation for the igxDropDown component. In order to allow the directive to handle all triggered events, it should be applied to the active (focused) element or a parent container. By default, a drop-down or its items don't take focus, so the directive can be placed on a button or input that will control the drop-down. The navigation directive value should target a component that is an instance or a descendant of the IgxDropDownBaseDirective class.

    The following sample demonstrates an input that opens and closes the igxDropDown instance on click. Applying the igxDropDownItemNavigation directive on the input itself will enable keyboard navigation when using the up and down arrow keys. This relies on the default drop-down behavior with the allowItemsFocus property set to false to allow the input to maintain focus.

    <!-- input-dropdown.component.html -->
    <igx-input-group #inputGroup [igxToggleAction]="dropDown">
      <input
        type="text"
        igxInput
        [igxDropDownItemNavigation]="dropDown"
        readonly="true"
        placeholder="choose an option"
        [value]="dropDown.selectedItem?.value"
        (keydown.ArrowDown)="openDropDown()"
      />
    
      <igx-suffix igxIconButton="flat" igxRipple>
        <igx-icon>arrow_drop{{ dropDown.collapsed ? '_down' : '_up' }}</igx-icon>
      </igx-suffix>
    </igx-input-group>
    
    <span>Selected: {{ dropDown.selectedItem?.value }}</span>
    <igx-drop-down #dropDown [width]="'160px'">
      <igx-drop-down-item *ngFor="let item of items" [value]="item.field">
        {{ item.field }}
      </igx-drop-down-item>
    </igx-drop-down>
    
    // input-dropdown.component.ts
    export class InputDropDownComponent {
      @ViewChild(IgxDropDownComponent) public igxDropDown: IgxDropDownComponent;
      @ViewChild('inputGroup', { read: IgxInputGroupComponent })
      public inputGroup: IgxInputGroupComponent;
    
      public items: Array<{ field: string }> = [
        { field: 'Option 1' },
        { field: 'Option 2' },
        { field: 'Option 3' },
      ];
    
      public openDropDown() {
        if (this.igxDropDown.collapsed) {
          this.igxDropDown.open({
            modal: false,
            positionStrategy: new ConnectedPositioningStrategy({
              target: this.inputGroup.element.nativeElement,
            }),
          });
        }
      }
    }
    

    A aplicação da diretiva garantirá que as seguintes ações sejam executadas como resultado da navegação pelo teclado:

    Nome Descrição
    Enter Selecione o item no menu suspenso e feche o menu suspenso.
    Space Selecione o item no menu suspenso e feche o menu suspenso.
    Esc Fecha o menu suspenso.
    Arrow Down Navegue até o próximo item no componente de destino.
    Arrow Up Navegue até o item anterior no componente de destino.
    End Navegue até o último item no componente de destino.
    Home Navegue até o primeiro item no componente de destino.

    When the allowItemsFocus property is enabled, the drop down items gain tab index and are focused when active. The focused drop-down items are the ones that trigger events, during keyboard navigation, which means that the navigation directive should be applied on the individual drop-down items.

    <igx-input-group [igxToggleAction]="dropDown">
      <input igxInput type="text" />
    </igx-input-group>
    <igx-drop-down #dropDown [allowItemsFocus]="true">
      <igx-drop-down-item *ngFor="let p of provinceData" [igxDropDownItemNavigation]="dropDown">
        {{ p }}
      </igx-drop-down-item>
    </igx-drop-down>
    

    Estilização

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

    Propriedade primária Propriedade dependente Descrição
    $background cor
    $item-text-color A cor do texto do item suspenso.
    $hover-itens-contexto O menu suspenso do item de fundo do curso.
    $focused-item-contexto O menu suspenso focava na cor de fundo do item.
    $focused-item-texto-cor O menu suspenso focava na cor do texto do item.
    $selected-Contexto de item O menu suspenso selecionou a cor de fundo do item.
    $disabled-item-texto-cor O menu suspenso desativou a cor do texto dos itens.
    $header-cor-texto A cor do texto do cabeçalho suspenso.
    $item-text-color
    $item-cor-ícone- A cor do ícone do item suspenso.
    $hover-item-texto-cor O item suspenso paira na cor do texto.
    $hover-item-ícone-cor O item suspenso paira na cor do ícone do cursor.
    $selected-Contexto de item
    $selected-item-text-color O menu suspenso selecionou a cor do texto do item.
    $selected-item-ícone-cor O menu suspenso selecionou a cor do ícone do item.
    $selected-hover-item-background O menu suspenso selecionou o item passando o mouse sobre a cor de fundo.
    $selected-passar-surto-item-text-color O menu suspenso selecionou o item para passar o mouse na cor do texto.
    $selected-passar o rato-ico-ícone-icônico-cor O menu suspenso seleciona o item de cor do ícone de passageiro.
    $selected-foco-item-fundo O menu suspenso seleciona o item foca na cor de fundo.
    $selected-foco-item-texto-cor O menu suspenso selecionou a cor do texto do foco do item.
    $focused-item-cor-borda- O item suspenso focava na cor da borda.

    Using the Ignite UI for Angular Theming, we can greatly alter the drop-down appearance. First, in order for us to use the functions exposed by the theme engine, we need to import the index file in our style file:

    @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 drop-down-theme and accepts some of the default theme's parameters. When you provide a certain background color, the theme automatically calculates the state colors and appropriate contrasting foregrounds. By setting the $background property, you'll get a fully styled dropdown.

    $custom-drop-down-theme: drop-down-theme(
      $header-text-color: #345779,
      $item-text-color: #2dabe8,
      $hover-item-text-color: #345779,
      $selected-item-background: #345779,
    );
    

    O último passo é passar o tema suspenso personalizado para um seletor de classe ou elemento:

    .drop-down__scroll-container {
      @include css-vars($custom-drop-down-theme);
    }
    

    Demo

    API Summary

    Theming Dependencies

    Additional Resources

    Nossa comunidade é ativa e sempre acolhedora para novas ideias.