Search code examples
angularionic-frameworkionic2floating-action-button

ionic / angular2 dynamically close FABs


Using ionic's FABS but in a loop, so can not use id for retrieving component and close:

<ion-item ion-item *ngFor="let e of elements">
    <ion-fab top right>
        <button ion-fab mini><ion-icon name="more"></ion-icon></button>
        <ion-fab-list side="bottom">
            <button ion-fab (click)="click(e)"><ion-icon name='create'></ion-icon></button>
        </ion-fab-list>
    </ion-fab>
</ion-item>

The standard solution for closing FABs require an ID on ION-FAB, then can access outer ION-FAB component and call .close():

    <ion-fab top right #fab>
        <button ion-fab mini><ion-icon name="more"></ion-icon></button>
        <ion-fab-list side="bottom">
            <button ion-fab (click)="click(fab,e)"><ion-icon name='create'></ion-icon></button>
        </ion-fab-list>
    </ion-fab>

Since these fabs are dynamically generated I can not provide an ID and don't know how to access the parent ION-FAB Component from inner button event, so how can I access parent FAB component to call .close() on it?


Solution

  • Try this HTML

    <ion-fab top right *ngFor="let e of elements; let currentIndex = index;"
    [style.margin-left.px]="currentIndex*45" #fabList>
            <button ion-fab mini id="{{'fab_btn'+ currentIndex}}"><ion-icon name="more"></ion-icon></button>
            <ion-fab-list side="bottom">
                <button ion-fab (click)="click(currentIndex)"><ion-icon name='create'></ion-icon></button>
            </ion-fab-list>
    </ion-fab>
    

    Typescript

    import { ViewChildren, QueryList } from '@angular/core';
    
    @ViewChildren('fabList')fabList : QueryList<FabContainer>; //Use @ViewChildren instead of @ViewChild
    
    click(currentIndex: any) {
        //let id = 'fab_btn' + currentIndex.toString();
        //document.getElementById(id).click();
        let currentFab: FabContainer = this.fabList._results[index]; //Get current clicked FabContainer object from index 
        currentFab.close(); 
    }
    

    Demo - https://stackblitz.com/edit/ionic-fab-tab-open-niy8wg-close-dynamically-utrxfs?file=pages/home/home.ts