[英]Hide angular material mat-tab using directive
我正在使用角材料选项卡,我想使用指令动态隐藏选项卡元素。
html模板
<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({
selector: '[appHideMe]'
})
export class HideMeDirective implements AfterViewInit {
constructor(
private el: ElementRef
) { }
ngAfterViewInit() {
this.el.nativeElement.style.display = 'none';
}
}
在编译期间, mat-tab
被替换,因此display = 'none'
将不起作用。 有什么方法可以像*ngIf
那样隐藏mat-tab
吗(使用HideMeDirective
)?
这是一个堆栈闪电战示例。
我还希望mat-tab
可以切换。 在这个例子中,我希望third
是可见的,但它不是。
模板
<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({
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';
}
}
只要div上没有HideMeDirective
,就会显示mat-dat
。 添加HideMeDirective
(参见第三个mat-tab
),元素不可见。 有任何想法吗?
尝试这样的事情
定义一个变量
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();
}
}
然后使用模板引用
<mat-tab appHideMe #ref="appHideMe" label="First"> Content 1 </mat-tab>
<mat-tab *ngIf="ref.hide" label="Second"> Content 2 </mat-tab>
那这个呢:
<mat-tab-group>
<mat-tab appHideMe label="First"> Content 1 </mat-tab>
<div appHideMe>
<mat-tab label="Second"> Content 2 </mat-tab>
</div>
<mat-tab label="Third"> Content 3 </mat-tab>
</mat-tab-group>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.