How to use native Bootstrap 4 Tab control in an Angular CLI project?

Before we begin this tutorial let me first make it clear that in order for you to be able to grasp and use this how-to you must have a little experience on Angular, Typescript and HTML scripting.  Furthermore, you must have some idea on how to setup the Angular CLI environments.  If not, please go to the official Angular site.  I had to do this, because, I’ve read lots of comments on how can we f$#% use the posts in our projects.

How to use native Bootstrap 4 Tab control in an Angular CLI project without having to create your own or download external components is very easy.  We only need one tool to achieve this, that tool is our plain old ngClass.

Here are the steps:

1.) Declare a boolean array that will hold your tab index.  Just provide a default active tab by setting any of the array items to true.

public tabIndex = new Array(true, false, false, false);

2.) Create a method that will be used to read click event on the tab control.

public tabIndexClick(index: number)
{
    for (var i = 0; i <= this.tabIndex.length - 1; i++) {
      if(index==i) this.tabIndex[i] = true;
      else this.tabIndex[i] = false;
    }
}

3.) Now construct the tab.  Take note of the ngClass directive, it uses an object, meaning you can add more classes.

<ul class="nav nav-tabs" role="tablist" style="width:100%">
	<li class="nav-item">
<a [ngClass]="{'active': tabIndex[0], 'nav-link': true }" (click)="tabIndexClick(0)" data-toggle="tab" role="tab">Tab1</a></li>
	<li class="nav-item">
<a [ngClass]="{'active': tabIndex[1], 'nav-link': true }" (click)="tabIndexClick(1)" data-toggle="tab" role="tab">Tab2</a></li>
	<li class="nav-item">
<a [ngClass]="{'active': tabIndex[2], 'nav-link': true }" (click)="tabIndexClick(2)" data-toggle="tab" role="tab">Tab3</a></li>
	<li class="nav-item">
<a [ngClass]="{'active': tabIndex[3], 'nav-link': true }" (click)="tabIndexClick(3)" data-toggle="tab" role="tab">Tab4</a></li>
</ul>

Thats it!  Have fun coding and Happy new year to all! And if you find this blog helpful, you can make the donation by clicking the Paypal button below.


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s