要在Angular 8中使用指令隐藏元素,您可以按照以下步骤进行操作:
hide.directive.ts
的指令文件,并在其中编写以下代码:import { Directive, ElementRef, Input, OnInit } from '@angular/core';
@Directive({
selector: '[appHide]'
})
export class HideDirective implements OnInit {
@Input() appHide: boolean;
constructor(private elementRef: ElementRef) {}
ngOnInit() {
this.hideElement();
}
private hideElement() {
if (this.appHide) {
this.elementRef.nativeElement.style.display = 'none';
}
}
}
元素,可以在该元素上添加appHide
指令,如下所示:
这是要隐藏的元素
- 在需要使用该指令的模块中导入和声明
HideDirective
。例如,在您的app.module.ts
文件中,添加以下代码:
import { NgModule } from '@angular/core';
import { HideDirective } from './hide.directive';
@NgModule({
declarations: [
HideDirective
],
imports: [
// 其他导入模块
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
现在,当appHide
属性设置为true
时,指令将隐藏指定的元素。
希望这可以帮助到您!
相关内容