Tor G
Tor G

Reputation: 31

Angular 7 *ngIf condtion based on active tab

I'm trying to show or hide a button depending on which tab is currently active. It works after clicking around the different tabs, but on load it does not display the button or the content of the default tab.

I'm using mat-toolbar and mat-tabs. The order of the tabs are:

(button) | Editor | Graph | something | somethin 2 | (button)

Here the (button) would be conditional based on active tab.

tabs.component.html:

<mat-toolbar color="primary" class="example-toolbar">
  <button *ngIf="editContent" mat-icon-button (click)="snav.toggle()"><mat-icon>menu</mat-icon></button>
  <h1 class="example-app-name">Responsive App</h1>

  <mat-tab-group animationDuration="0ms" class="tabs" (selectedTabChange)="showContent($event)" [selectedIndex]="0">
    <mat-tab label="Editor" ></mat-tab>
    <mat-tab label="Something"></mat-tab>
    <mat-tab label="Graph" ></mat-tab>
    <mat-tab label="Something" ></mat-tab>
  </mat-tab-group>
  <span class="example-spacer"></span>

  <button mat-icon-button (click)="srnav.toggle()" class="rightBtn"><mat-icon>menu</mat-icon></button>
</mat-toolbar>

<mat-sidenav-container class="example-sidenav-container">
  <mat-sidenav #snav [fixedInViewport]="mobileQuery.matches" fixedTopGap="56">
    <mat-nav-list>
      <a mat-list-item routerLink="." *ngFor="let nav of fillerNav">{{nav}}</a>
    </mat-nav-list>
  </mat-sidenav>

  <mat-sidenav-content>
  <!-- Show content -->
    <app-content *ngIf="this.editContent"></app-content>
    <app-graph *ngIf="this.graphContent"></app-graph>
  </mat-sidenav-content>
</mat-sidenav-container>

tabs.component.ts:

//declaring variables
    editContent:boolean = false;
    graphContent:boolean = false;

    ......


    showContent(indicator):void{
        this.graphContent = false;
         this.editContent = false;
        switch(indicator.index) { 
       case 0: { 
          this.editContent = true;
          break; 
       }
       case 1:{
         break;
       }
       case 2: { 
          this.graphContent = true;
          break; 
       }
       case 3:{
         break;
       }
       default: { 
          console.log(indicator.index);
          break; 
       } 
     } 

Upvotes: 0

Views: 2966

Answers (1)

Tor G
Tor G

Reputation: 31

From comments: Thanks, i forgot about that. I managed to fix it! It was a stupid mistake and i'm quite tired hehe. The fix, if anyone is wondering, was to set values to the variables in ngInit. Also use a variable for the "selectedIndex"

Upvotes: 0

Related Questions