deidara song
deidara song

Reputation: 209

Angular - how to deny access to tabPanel in tabView on tab click

I have a tabview with some tabpanels in it. I can control it programmatically using [activeIndex] The problem I'm having is that when I click on a tab, I should display an alert and deny access to this tab if a variable is set to false. I can show the alert fine however I can also see and access the tab. Is there a way when you click on the tab, it just shows the alert and denies access to the tab(not show it's contents and just stay on the current tab).

I'm using Angular 6 with PrimeNG

HTML:

<p-tabView [activeIndex]="activeindex" (onChange)="handleChange($event)">
    <p-tabPanel header="I am Tab1" [disabled]="isAllowedAccess">
        <app-tab1-contents></app-tab1-contents>
    </p-tabPanel>
    <p-tabPanel header="I am Tab2(I need to deny access if var is false)" [disabled]="isAllowedAccess">
        <app-tab2-request></app-tab2-request>
    </p-tabPanel>
</p-tabView>

TYPESCRIPT:

handleChange(e: any) {

    if (e.index == 1) //target the second tab
     {
        if (this.sampleVariable == false) {
            //just show the alert box and hide tab contents
            alert('Access Denied');
            //tried redirecting to another tab but it doesn't work
            e.index = 0;
        } else {
            //allow access, show tab contents
        }
    }
}

Upvotes: 1

Views: 3046

Answers (1)

Vincent Tescari
Vincent Tescari

Reputation: 21

In your HTML, you need to add a name to the tabview with '#'. Example :

 <p-tabView [activeIndex]="activeindex" #tabView (...)

In second time, in your ts code, declare the tabview :

 @ViewChild('tabView') tabview: TabView;

Then, in your method, modify to :

handleChange(e: any) {

if (e.index == 1) //target the second tab
 {
    if (this.sampleVariable == false) {
        //just show the alert box and hide tab contents
        alert('Access Denied');
        //redirecting to another tab with tabview declared as viewchild of HTML side
        this.tabview.activeIndex = 0;
    } else {
        //allow access, show tab contents
    }
}

}

Upvotes: 1

Related Questions