Thursday, January 11, 2018

How may I conditionally prevent users from changing Bootstrap tabs in an Angular 4 application?

What I erroneous refer to as an ARIA Tab Panel here is just the Bootstrap 4 way of setting up in-page tabs. The individual tabs look like this:

<li class="nav-item">
   <a class="nav-link" id="benefits-tab" data-toggle="tab" href="#benefits" role="tab"
         aria-controls="benefits" aria-expanded="true">Benefits</a>
</li>

 
 

Me may revamp like so for the desired effect.

<li class="nav-item">
   <a class="nav-link" id="benefits-tab" [attr.data-toggle]="isWhatever ? 'disabled' : 'tab'"
         href="#benefits" role="tab" aria-controls="benefits" aria-expanded="true"
         (click)="changeTabs($event)" onclick="return false;">Benefits</a>
</li>

 
 

isWhatever here will be our conditional for whether or not we wish to squawk if a user tries to change tabs (maybe they have unsaved work) and looping in isWhatever (use a better name in real code) is basically one of three changes which specifically are:

  • [attr.data-toggle]="isWhatever ? 'disabled' : 'tab'"
  • (click)="changeTabs($event)"
  • onclick="return false;"

 
 

In the first bullet above, disabled in lieu of tab means nothing. You could just use x instead of disabled as the point is that we are not using tab in that case. The second bullet above has an event in it and that should look something like so at your component's TypeScript code:

changeTabs(event: any):void{
   if (event.target.className.indexOf("active") == -1){
      if (this.isWhatever){
         var result = confirm("Are you sure you want to leave?");
         if (result) {
            this.stupidService.isToUseGuard = false;
            this.isWhatever = false;
         }
      }
   }
}

 
 

The reason to hand in the current tab and check for the active CSS style is that you do not want to trigger this stuff if the user merely clicks on the tab he or she is already on for some silly reason. That act should be mundane as it is harmless. Also, stupidService here is going to be akin to stupidService here. You will probably want to use guards in your Angular app to prevent users from changing routes if you are also preventing them from changing tabs, so write the two implementations with each other in mind.

No comments:

Post a Comment