Descripción general de la directiva de autocompletado Angular

    Angular Autocomplete es una directiva de cuadro de búsqueda que permite a los usuarios encontrar, filtrar y seleccionar fácilmente un elemento de una lista de sugerencias mientras escriben. Es rica en funciones y admite la vinculación de datos, el filtrado, la agrupación, las opciones de personalización de la interfaz de usuario y otras funcionalidades integradas para que los desarrolladores puedan crear una experiencia de búsqueda de autocompletado intuitiva.

    The igxAutocomplete directive provides a way to enhance a text input by showing an igxDropDown with suggested options, provided by the developer. The suggestions will show once you start typing in the text input or use the Arrow Up/Arrow Down keys.

    Angular Autocomplete Example

    El siguiente ejemplo de autocompletar Angular genera una lista desplegable de sugerencias a medida que los usuarios comienzan a escribir el nombre de una ciudad en el cuadro de texto de entrada.

    Getting Started with Ignite UI for Angular Autocomplete

    Para comenzar con la directiva Ignite UI for Angular para Angular componentes y Autocompletar en particular, 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 IgxAutocompleteModule and IgxDropDownModule in our app.module. If igxAutocomplete is applied on an igxInput, the igxInputGroupModule is also required:

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

    Alternatively, as of 16.0.0 you can import the IgxAutocompleteDirective as a standalone directive.

    // home.component.ts
    
    ...
    import { IgxAutocompleteDirective, IGX_INPUT_GROUP_DIRECTIVES, IGX_DROP_DOWN_DIRECTIVES } from 'igniteui-angular';
    // import { IgxAutocompleteDirective, IGX_INPUT_GROUP_DIRECTIVES, IGX_DROP_DOWN_DIRECTIVES } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-home',
        template: `
        <igx-input-group>
            <input igxInput name="towns" type="text" [igxAutocomplete]="townsPanel" />
            <label igxLabel for="towns">Towns</label>
        </igx-input-group>
        <igx-drop-down #townsPanel>
            <igx-drop-down-item *ngFor="let town of towns">
                {{town}}
            </igx-drop-down-item>
        </igx-drop-down>
        `,
        styleUrls: ['home.component.scss'],
        standalone: true,
        imports: [IgxAutocompleteDirective, IGX_INPUT_GROUP_DIRECTIVES, IGX_DROP_DOWN_DIRECTIVES]
    })
    export class HomeComponent {}
    

    Now that you have the Ignite UI for Angular Action Strip module or directive imported, you can start with a basic configuration of the igxAutocomplete component.

    Using the Angular Autocomplete

    In order to apply the autocomplete functionality to an input, add the igxAutocomplete directive, referencing the dropdown:

    <igx-input-group>
        <input igxInput name="towns" type="text" [igxAutocomplete]="townsPanel" />
        <label igxLabel for="towns">Towns</label>
    </igx-input-group>
    <igx-drop-down #townsPanel>
        <igx-drop-down-item *ngFor="let town of towns">
            {{town}}
        </igx-drop-down-item>
    </igx-drop-down>
    

    Agregue la lista que se mostrará en el menú desplegable. Si desea que la lista se filtre mientras escribe, utilice la interfaz PipeTransform.

    import { Component, Pipe, PipeTransform } from '@angular/core';
    
    @Component({
        selector: 'app-autocomplete-sample',
        styleUrls: ['autocomplete.sample.css'],
        templateUrl: `autocomplete.sample.html`
    })
    export class AutocompleteSampleComponent {
        constructor() {
            this.towns = [ 'New York', 'Washington, D.C.', 'London', 'Berlin', 'Sofia', 'Rome', 'Kiev',
                'Copenhagen', 'Paris', 'Barcelona', 'Vienna', 'Athens', 'Dublin', 'Yerevan',
                'Oslo', 'Helsinki', 'Stockholm', 'Prague', 'Istanbul', 'El Paso', 'Florence', 'Moscow' ];
        }
    }
    
    @Pipe({ name: 'startsWith' })
    export class AutocompletePipeStartsWith implements PipeTransform {
        public transform(collection: any[], term = '') {
            return collection.filter((item) => item.toString().toLowerCase().startsWith(term.toString().toLowerCase()));
        }
    }
    
    Note

    The igxAutocomplete uses the igxDropDown as a provider for the available options, which means that all capabilities of the dropdown component can be used in the autocomplete.

    Disable Angular Autocomplete

    You can disable the Angular autocomplete by using the IgxAutocompleteDisabled input:

    <igx-input-group>
        <input igxInput name="towns" type="text"
            [igxAutocomplete]='townsPanel'
            [igxAutocompleteDisabled]="disabled"/>
        <label igxLabel for="towns">Towns</label>
    </igx-input-group>
    

    Autocomplete Settings

    The igx-autocomplete dropdown positioning, scrolling strategy, and outlet can be configured using the IgxAutocompleteSettings.

    In the following Angular Autocomplete example we will position the dropdown above the input and disable the opening and closing animations. We're using the ConnectedPositioningStrategy for this:

    <igx-input-group class="autocomplete">
        <label igxLabel for="cinema">Cinema</label>
        <input igxInput name="cinema" type="text"
        [igxAutocomplete]="townsPanel"
        [igxAutocompleteSettings]="settings"/>
    </igx-input-group>
    <igx-drop-down #townsPanel maxHeight="300px">
        <igx-drop-down-item-group *ngFor="let town of towns" [label]="town.name">
            <igx-drop-down-item *ngFor="let cinema of town.cinemas" [value]="cinema">
                {{cinema}}
            </igx-drop-down-item>
        </igx-drop-down-item-group>
    </igx-drop-down>
    
    export class AutocompleteComponent {
        public settings = {
            positionStrategy: new ConnectedPositioningStrategy({
                closeAnimation: null,
                openAnimation: null,
                verticalDirection: VerticalAlignment.Top,
                verticalStartPoint: VerticalAlignment.Top
            })
        };
    
        public towns = [
            {
              name: 'New York',
              cinemas: [
                'Regal Cinemas',
                'Village East Cinema',
                'Roxy Cinema',
                'The Paris Theatre'
            ]},
            {
                name: 'Los Angeles',
                cinemas: [
                    'Arc Light',
                    'Pacific Cinerama Dome',
                    'New Beverly Cinema',
                    'Downtown Independent'
            ]},
            {
                name: 'Seattle',
                cinemas: [
                    'Central Cinema',
                    'Grand Illusion Cinema',
                    'Ark Lodge Cinemas',
                    'Skyway Outdoor Cinema'
            ]}
        ];
    }
    
    Note

    The default positioning strategy is AutoPositionStrategy and the dropdown is opened according to the available space.

    Si todo salió bien, deberías ver esto en tu navegador:

    Keyboard Navigation

    • / o escribir la entrada abrirá el menú desplegable, si está cerrado.
    • - pasará al siguiente elemento desplegable.
    • - pasará al elemento desplegable anterior.
    • ENTER confirmará el elemento ya seleccionado y cerrará el menú desplegable.
    • ESC cerrará el menú desplegable.
    Note

    Cuando se abre el autocompletado Angular, se selecciona automáticamente el primer elemento de la lista. Lo mismo ocurre cuando se filtra la lista.

    También puede ver cómo nuestro App Builder ™WYSIWYG agiliza toda la historia del diseño a código en un 80% utilizando componentes de Angular reales.

    Compatibility support

    Applying the igxAutocomplete directive will decorate the element with the following ARIA attributes:

    • role="combobox" - rol del elemento donde se aplica la directiva.
    • aria-autocomplete="list" - indica que las sugerencias para completar la entrada se proporcionan en forma de lista
    • aria-haspopup="listbox" attribute to indicate that igxAutocomplete can pop-up a container to suggest values.
    • aria-expanded="true"/"false": valor que depende del estado contraído del menú desplegable.
    • aria-owns="dropDownID" - ID del menú desplegable utilizado para mostrar sugerencias.
    • aria-activededescendiente="listItemId" - el valor se establece en la identificación del elemento de la lista activa actual.

    The drop-down component, used as provider for suggestions, will expose the following ARIA attributes:

    • role="listbox" - applied on the igx-drop-down component container
    • role="group" - applied on the igx-drop-down-item-group component container
    • role="option" - applied on the igx-drop-down-item component container
    • aria-disabled="true"/"false" applied on igx-drop-down-item, igx-drop-down-item-group component containers when they are disabled.

    Estilismo

    Cada componente tiene su propio tema.

    To get the igxAutocomplete styled, you have to style its containing components. In our case, these are the input-group-theme and the drop-down-theme.

    Take a look at the igxInputGroup and the igxDropdown styling sections to get a better understanding of how to style those two components.

    API Reference

    Theming Dependencies

    Additional Resources

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