用于隐藏元素的 Angular 4 自定义指令不起作用

Gag*_*aur 2 angular

我正在创建一个自定义指令来隐藏某些条件下的元素,但它没有按照我在谷歌搜索中找到的指令工作。

所有其他工作正常但元素不影响显示属性

//use of directive
<div manAuthorized [permission]="'permission-string'" class="col-2 data-object-link">

// actual directive

@Directive({
  selector: '[manAuthorized]'
})
export class AuthorizedDirective implements OnInit {

  @Input() permission: string;
  private userObservable: Observable<UserAuthorizations>;
  private currentUser: any;

  constructor(private elementRef: ElementRef, private configService: ConfigService, private currentUserService: CurrentUserService) {
    this.userObservable = this.currentUserService.getCurrentUser();
  }

  ngOnInit(): void {
    this.userObservable.subscribe((user) => {
      this.currentUser = user;
      if (!this.authorized()) {
        this.elementRef.nativeElement.display = 'none';
      }
    });
  }

  private authorized() {
    return true;
  }
}
Run Code Online (Sandbox Code Playgroud)

Ani*_*Das 6

您需要处理具有显示的样式属性。当您尝试直接设置显示时,它不起作用。

this.elementRef.nativeElement.style.display = 'none';
Run Code Online (Sandbox Code Playgroud)

  • 我试图使用“viewContainerRef.clear()”调用,但它不起作用。你的解决方案确实有效。 (2认同)