Hide angular material mat-tab using directive

Discussão em 'Angular' iniciado por tprieboj, Fevereiro 18, 2025.

  1. tprieboj

    tprieboj Guest

    I am using angular material tabs and I want to use a directive to hide a tab element dynamically.

    html template

    <mat-tab-group>
    <!-- how to hide this using a directive? -->
    <mat-tab appHideMe label="First"> Content 1 </mat-tab>
    <!-- like this -->
    <mat-tab *ngIf="false" label="Second"> Content 2 </mat-tab>
    <mat-tab label="Third"> Content 3 </mat-tab>
    </mat-tab-group>

    <div appHideMe>
    hidden
    </div>
    <div>
    visible
    </div>


    HideMe directive

    @Directive({
    selector: '[appHideMe]'
    })
    export class HideMeDirective implements AfterViewInit {
    constructor(
    private el: ElementRef
    ) { }

    ngAfterViewInit() {
    this.el.nativeElement.style.display = 'none';
    }
    }


    As during compilation, mat-tab is replaced so display = 'none' will not work. Is there any way how to hide mat-tab like *ngIf does (using HideMeDirective)?

    Here is a stackblitz example.


    I also want mat-tab to be toggleable. In this example I expect third to be visible but it is not.

    template

    <mat-tab-group>
    <!-- how to hide this using directive? -->
    <div>
    <mat-tab label="First"> Content 1 </mat-tab>
    </div>
    <div appHideMe="hide">
    <mat-tab label="Second"> Content 2 </mat-tab>
    </div>
    <div appHideMe>
    <mat-tab label="Third"> Content 3 </mat-tab>
    </div>
    <div>
    <mat-tab label="Fourth"> Content 4 </mat-tab>
    </div>

    </mat-tab-group>

    <div appHideMe>
    hidden
    </div>
    <div>
    visible
    </div>


    directive code

    @Directive({
    selector: '[appHideMe]'
    })
    export class HideMeDirective implements AfterViewInit {

    @Input() appHideMe: string;

    constructor(
    private el: ElementRef
    ) { }

    ngAfterViewInit() {

    if (this.appHideMe === 'hide') {
    this.el.nativeElement.style.display = 'none';
    }
    // should be displayed
    // this.el.nativeElement.style.display = 'none';
    }
    }


    As long as there is no HideMeDirective on div, mat-dat will be displayed. When HideMeDirective is added (see third mat-tab), that element is not visible. Any ideas?

    Continue reading...

Compartilhe esta Página