Angular Descripción general de la directiva de alternancia

    La directiva Ignite UI for Angular Toggle permite a los usuarios hacer que un contenedor en el DOM se pueda alternar a través de la interacción del usuario.

    Angular Toggle Example

    Getting Started with Ignite UI for Angular Toggle

    Para comenzar con la directiva Ignite UI for Angular Toggle, 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 IgxToggleModule in your app.module.ts file.

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

    Alternatively, as of 16.0.0 you can import the IgxToggleDirective as a standalone dependency.

    // home.component.ts
    
    import { IgxToggleDirective, IgxButtonDirective } from 'igniteui-angular/directives';
    
    // import { IgxToggleDirective, IgxButtonDirective } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-home',
        template: `
        <button class="toggle-button" igxButton="contained" (click)="toggleContent()">Toggle</button>
        <div class="toggle-content" igxToggle>
            <section class="toggle-section">
                <img src="assets/images/toggle/nature.jpg" alt="Nature" />
            </section>
        </div>
        `,
        styleUrls: ['home.component.scss'],
        standalone: true,
        imports: [IgxToggleDirective, IgxButtonDirective]
    })
    export class HomeComponent {}
    

    Now that you have the Ignite UI for Angular Toggle module or directive imported, you can start using the igxToggle directive.

    Using the Angular Toggle Directive

    Display Toggle

    Para mostrar y ocultar el contenido de alternancia, utilice sus métodos de apertura y cierre:

    import { IgxToggleDirective } from 'igniteui-angular/directives'
    // import { IgxToggleDirective } from '@infragistics/igniteui-angular'; for licensed package
    ...
    
    export class Class {
        @ViewChild(IgxToggleDirective) toggle: IgxToggleDirective;
    
        toggleContent() {
            if (this.toggle.collapsed) {
                this.toggle.open();
            } else {
                this.toggle.close();
            }
        }
    }
    

    Luego, en la plantilla de nuestro componente, podemos aplicar la directiva sobre el elemento que queremos que sea alternable:

    <!--template.component.html-->
    <button class="toggle-button" igxButton="contained" (click)="toggleContent()">Toggle</button>
    <div class="toggle-content" igxToggle>
        <section class="toggle-section">
            <img src="assets/images/toggle/nature.jpg"/>
        </section>
    </div>
    

    Examples

    Change Position

    En el siguiente ejemplo, usaremos una estrategia de posicionamiento diferente para que el contenido se muestre debajo del botón.

    The igxToggle directive uses the IgxOverlayService provider. The open, close and toggle methods accept optional overlay settings that control how the content is displayed. If omitted, the default overlay settings are used as seen in the previous sample.

    Note

    By default, the closeOnOutsideClick property is set to true. In order to disable this functionality, the property has to be set to false. Additionally, the closeOnEscape property defaults to false, so in order to make use of it, we have to set it to true.

    // template.component.ts
    
    ...
        @ViewChild(IgxToggleDirective) public igxToggle: IgxToggleDirective;
        @ViewChild('button') public igxButton: ElementRef;
    
        public _positionSettings = {
            horizontalStartPoint: HorizontalAlignment.Left,
            verticalStartPoint: VerticalAlignment.Bottom
        };
    
        public _overlaySettings = {
            target: this.igxButton.nativeElement,
            closeOnOutsideClick: false,
            closeOnEscape: true,
            positionStrategy: new ConnectedPositioningStrategy(this._positionSettings)
        };
    
        public toggle() {
            this.igxToggle.toggle(this._overlaySettings);
        }
    

    Así es como debería verse nuestra palanca ahora:

    Automatic Toggle Actions

    In order to avoid using the open and close methods, we can use a directive, which has an onClick handler, and changes the state of the toggle we are referring to automatically.

    If we would like to take advantage of this functionality, we will have to use the IgxToggleActionDirective from the IgxToggleModule and assign the IgxToggleDirective to it.

    Note

    The IgxToggleActionDirective should be declared on the element we are planing to use like a trigger (toggle).

    <!--template.component.html-->
    <button class="toggle-button"  igxButton="contained" [igxToggleAction]="toggleRef">Toggle</button>
    <div class="toggle-content" igxToggle #toggleRef="toggle">
        <section class="toggle-section">
            <h6>Automatic toggle actions</h6>
        </section>
    </div>
    

    Después de estos cambios, la palanca debería funcionar exactamente de la misma manera.

    Note

    By default IgxToggleActionDirective excludes its host element from the closeOnOutsideClick property. Therefore, clicking on the host element will not fire any event. Additionally, this directive will set its host element as the overlay settings target.

    Automatic Toggle Service Provider

    There is a convenient way to keep the state of the igxToggle directive and command it via the igxNavigationService provider. We just need to set an identifier for our igxToggle element, which will be used to register the toggle with the service. If we would like to control its state automatically, we have to pass this identifier to the igxToggleActionDirective.

    <!--template.component.html-->
    <button igxToggleAction="toggleId" class="toggle-button" igxButton="contained">Toggle</button>
    <div igxToggle id="toggleId" class="toggle-content">
        <section class="toggle-section">
            <h6>Toggled by the service provider</h6>
        </section>
    </div>
    

    Si todo ha ido bien, quedará así:

    Offsetting the Toggle Container

    We can manipulate the position of the toggle container along the corresponding axis by a provided amount. The setOffset method also supports an optional offsetMode parameter that determines whether to add to the current offset values or set them to a specific value.

    // deltaX and deltaY determine by how much the container will be offset compared to its' previous position
    // Using OffsetMode.Add to add the values (default behavior)
    public offsetToggleAdd() {
        const deltaX = 30;
        const deltaY = 30;
        this.toggle.setOffset(deltaX, deltaY, OffsetMode.Add);
    }
    
    // deltaX and deltaY determine the exact position to set the container to, relative to its target element.
    // Using OffsetMode.Set to set the offset to specific values
    public offsetToggleSet() {
        const deltaX = 30;
        const deltaY = 30;
        this.toggle.setOffset(deltaX, deltaY, OffsetMode.Set);
    }
    

    API References

    Componentes adicionales y/o directivas con API relativas que se utilizaron:

    Theming Dependencies

    Additional Resources

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