angularangular-materialselectedindex

SelectedIndex mat-tab doesn’t work in ngif


Good day, I need initialize my mat-tab in the first tab, but I can´t when I use *ngIf.

This is my code :

html

<mat-tab-group dynamicHeight> 

  <mat-tab label="RENT" *ngIf="showRent"> 
  
    <div class="rc-result" > 
  
      <mat-card class="rc-available"> 
  
        {{rent}} 
  
      </mat-card> 
  
    </div> 
  
  </mat-tab> 
  
  <mat-tab label="FILTERS"> 
  
    <div class="rc-result" > 
    
        <mat-card class="rc-available"> 
    
          {{filters}} 
    
        </mat-card> 
    
    </div> 
  
  </mat-tab> 
  
</mat-tab-group> 

component.ts

import { Component, OnInit, ViewChild } from '@angular/core'; 
    
import { MatTabGroup} from '@angular/material/tabs'; 
    

my variables

  @ViewChild(MatTabGroup) tabGroup!: MatTabGroup; 
  showRent: Boolean = false; 

in the ngOnInit. Depend on the origin of data the tab initialize in cero or one.

        this._bridge.sentParams 
                     .subscribe((payload: any) => { 
                        this.myPayloadForm = payload. Data;  
                        if (this.myPayloadForm.home === 'ahri'){ 
                          this.showRent = false;                                                
                          this.tabGroup.selectedIndex = 1; 
                        } else { 
                          this.showRent = true;                                                          
                          this.tabGroup.selectedIndex = 0; 
                        }           
             }); 
       } 
    

I appreciate your support and interest in helping me


Solution

  • After setting the value for showRent set the selectedIndex and call the detectChanges from ChangeDetectorRef

    this.showRent = false;                                                
    this.tabGroup.selectedIndex = 1;
    this.changeDetector.detectChanges();
    

    Create ChangeDetectorRef object in the constructor of your component.ts file enter image description here