简体   繁体   中英

Get access to tab element inside a modal in ng-bootstrap

I'm using ng-bootstrap with Angular 2. I can't access to the #tabs variable from my component using @ViewChild . This only happens when I use the tab directive inside the modal directive. Here is my code:

auth.component.html

<template #modal let-c="close" let-d="dismiss">
        <div class="modal-header">
            <h4 class="modal-title"></h4>
            <button type="button" class="close" aria-label="Close" (click)="close()">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-body">
            <ngb-tabset #tabs="ngbTabset" (tabChange)="changeTabs($event)">
                <ngb-tab title="Login" id="login">
                    <template ngbTabContent>
                        ...
                    </template>
                </ngb-tab>
                <ngb-tab title="Sign up" id="signUp">
                    <template ngbTabContent>
                       ...
                    </template>
                </ngb-tab>
            </ngb-tabset>                
        </div>
    </template>

auth.component.ts

import {Component, ViewChild} from '@angular/core';
import {NgbModal} from "@ng-bootstrap/ng-bootstrap";

@Component({
    moduleId: module.id,
    selector: 'st-auth',
    templateUrl: 'auth.component.html'
})

export class AuthComponent {

    /*
     * ------------ FIELDS -----------------
     */

    @ViewChild('modal') modal;
    private modalElement:any;

    @ViewChild('tabs') tabs;
    private tabsElement:any;


    /*
     * ------------ INITIALIZE -----------------
     */

    ngAfterViewInit() {
        this.modalElement = this.modal;
        this.tabsElement = this.tabs;

        console.log(this.tabs); //show 'undefined'
    }

    constructor(private modalService: NgbModal) {}
}

I faced the same issue. When using a < template > element, angular does not treat this as a normal DOM element, so you cannot access it via the ViewChild decorator. What I ended up doing was to create a new component with the dialog content and passed this component to modalService.open(). An example can be seen here .

Hint: Don't forget to add your modal-component to the entryComponents array of your module

Try using an variable "active: boolean" and function "changeTabs()" to change value active, ex:

HTML:

<tabset>
       <tab id="tab1" [disabled]="activeTab"  [active]="!activeTab">....</<tab>
       <tab id="tab2" [disabled]="!activeTab"  [active]="activeTab">....</<tab>
</tabset>
<button type="button" class="btn btn-success" (click)="changeTabs()"> ChangeTab</button>

TS

activeTab: boolean = false;

changeTabs(){
    this.activeTab= !this.activeTab;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM