I am using angular material tabs and I want to use directiveto hide tab element dynamically.
html template
<mat-tab-group>
<!-- how to hide this using 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
), element is not visible. Any ideas?
Try Something like this
Define one variable
import { Directive, ElementRef, AfterViewInit,ChangeDetectorRef } from '@angular/core';
@Directive({
selector: '[appHideMe]',
exportAs:'appHideMe',
})
export class HideMeDirective implements AfterViewInit {
hide:Boolean;
constructor(
private el: ElementRef,
private cdr:ChangeDetectorRef
) { }
ngAfterViewInit() {
this.hide=false;
this.cdr.detectChanges();
}
}
Then use template ref
<mat-tab appHideMe #ref="appHideMe" label="First"> Content 1 </mat-tab>
<mat-tab *ngIf="ref.hide" label="Second"> Content 2 </mat-tab>
Example:https://stackblitz.com/edit/angular-mqc1co-vlw9aa
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With