Reputation: 1826
I am trying to create a tab in angular 6 but when the app first loads all the tabs are visible and the links do not work.
<div ng-init="tab=1">
<div class="cb" ng-click="tab = 1">
<a [routerLink]='["/search"]' (click)='collapse()'>
<span class='glyphicon glyphicon-search'></span> Search
</a>
</div>
<div class="cb" ng-click="tab = 2">
<a [routerLink]='["/"]' (click)='collapse()'>
<span class='glyphicon glyphicon-home'></span> Home
</a>
</div>
<div ng-show="tab == 1">
<app-search-component></app-search-component>
</div>
<div ng-show="tab == 2">
<p>secondb</p>
</div>
</div>
Upvotes: 0
Views: 13330
Reputation: 22078
Here is a generic tabs example written in angular 4+ and angular material library (version 2):
tabs.html:
<nav mat-tab-nav-bar class="tabs">
<a mat-tab-link class="tab"
*ngFor="let link of routeLinks"
[routerLink]="link.link"
[active]="activeLinkIndex == link.index"
>
{{link.label}}
</a>
</nav>
tabs.ts:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector : 'tabs',
templateUrl : './tabs.component.html',
styleUrls : ['./tabs.component.scss']
})
export class TabsComponent implements OnInit {
routeLinks: any[];
activeLinkIndex = -1;
constructor(
private router : Router
){
this.routeLinks = [
{
label : 'Tab 1',
link : './tab-1-link',
index : 0
},
{
label : 'Tab 2',
link : './tab-2-link',
index : 1
},
{
label : 'Tab 3',
link : './tab-3-link',
index : 2
}
];
}
ngOnInit() {
this.activeLinkIndex = this._markingTabLogic(this.router);
this.router.events.subscribe((res) => {
//A bit generic url matching
//this.activeLinkIndex =this.routeLinks.indexOf(this.routeLinks.find(tab => tab.link === '.' + this.router.url));
//A more fine grain matching
this.activeLinkIndex = this._markingTabLogic(this.router);
});
}
_markingTabLogic(router){
if(router.url.indexOf('tab-3-link') > -1){
return 2;
}
else if(router.url.indexOf('tab-2-link') > -1){
return 1;
}
return 0;
}
}
also don't forget to import angular material in your components module (the module of your tabs component):
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule} from '@angular/router';
import {MatTabsModule} from '@angular/material/tabs';
import {TabsComponent} from "./tabs/tabs.component";
@NgModule({
imports: [
CommonModule,RouterModule,MatTabsModule]
declarations: [TabsComponent]
})
export class ComponentsModule { }
If you need a tutorial - check this: https://www.nikhildevre.com/creating-tabs-using-angular-material-5-and-angular-5-routing/
Upvotes: 1