9

I am creating a custom directive to hide elements on certain conditions but its not working as per the instruction i found googling.

All other things working but element is not effecting display property

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;
  }
}
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
Gagandeep Kaur
  • 172
  • 1
  • 1
  • 8
  • 2
    in my opinion better approach would be to use viewcontainerref.clear() a great example here https://netbasal.com/the-power-of-structural-directives-in-angular-bfe4d8c44fb1 – Karan Garg Jul 17 '17 at 16:21
  • Another post showing an alternative approach: https://stackoverflow.com/questions/43517660/directive-that-works-as-ng-if-angular-2 – Alexander Nied Jan 06 '22 at 21:41

2 Answers2

14

You need to handle the style property which have display. as you are trying to set display directly, it did not work.

this.elementRef.nativeElement.style.display = 'none';
artemnih
  • 4,136
  • 2
  • 18
  • 28
Aniruddha Das
  • 20,520
  • 23
  • 96
  • 132
1
constructor(private ref: ElementRef<HTMLElement>) {}
ngAfterViewInit(): void {
  if (isTeamsWindow()) this.ref.nativeElement?.remove();
}

should do it but weird that viewContainerRef does not work.

Venipa
  • 23
  • 1
  • 1
  • 5