gpt4 book ai didi

html - 使用指令隐藏 Angular Material mat-tab

转载 作者:太空狗 更新时间:2023-10-29 19:32:33 24 4
gpt4 key购买 nike

我正在使用 Angular Material 选项卡,我想使用指令动态隐藏选项卡元素。

html模板

<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({
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)?

Here是一个 stackblitz 示例。


我还希望 mat-tab 可以切换。在 this示例 我希望 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>

示例:https://stackblitz.com/edit/angular-mqc1co-vlw9aa

关于html - 使用指令隐藏 Angular Material mat-tab,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51872513/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com