Visão geral da diretiva Angular Toggle

    A diretiva Ignite UI for Angular Toggle permite que os usuários tornem um contêiner no DOM alternável por meio da interação do usuário.

    Angular Toggle Example

    Getting Started with Ignite UI for Angular Toggle

    Para começar a usar a diretiva Ignite UI for Angular Toggle, 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 issoIgxToggleModule no seu arquivo app.module.ts.

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

    Alternativamente,16.0.0 você pode importar comoIgxToggleDirective uma dependência independente.

    // 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 e ocultar o conteúdo de alternância, use seus métodos de abertura e fechamento:

    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();
            }
        }
    }
    

    Então, no modelo do nosso componente, podemos aplicar a diretiva no elemento que queremos que seja ativado:

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

    No próximo exemplo, usaremos uma estratégia de posicionamento diferente para que o conteúdo seja exibido abaixo do botão.

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

    É assim que nossa alternância deve ficar agora:

    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>
    

    Após essas alterações, o botão deverá funcionar exatamente da mesma maneira.

    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>
    

    Se tudo correr bem, ficará assim:

    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 e/ou diretivas adicionais com APIs relativas que foram usadas:

    Theming Dependencies

    Additional Resources

    Nossa comunidade é ativa e sempre acolhedora para novas ideias.