1

I have a button that I need to give permission to a specific user If he logs in into a website. I can do this with *ngIf on the HTML file but I would like to give the HTML element an id and then do the permission operation on the .ts file.

<ul class="navbar-nav float-right" *ngIf="user.name === 'John'" >
  <li class="nav-item" >
    <a class="nav-link" routerLink="Private">Private</a>
  </li>
</ul>

Thanks in advance.

Saruman
  • 61
  • 1
  • 8

3 Answers3

0

You can use template ref syntax in your html file. And use ViewChild at your component code.

<ul class="navbar-nav float-right" #privateUL>
  <li class="nav-item" >
    <a class="nav-link" routerLink="Private">Private</a>
  </li>
</ul>

--

  @ViewChild("privateUL", { static: false }) ul: ElementRef;

  ngAfterViewInit() {
    // modify your element
    this.ul.nativeElement.style.backgroundColor = "blue";
  }

Check this stackblitz sample.

Eldar
  • 9,781
  • 2
  • 10
  • 35
0

HTML

 <ul class="navbar-nav float-right" id="ulPrivate">
      <li class="nav-item" >
        <a class="nav-link" routerLink="Private">Private</a>
      </li>
    </ul>

TS

const el: HTMLElement = document.getElementById('ulPrivate');
el.setAttribute("style", "color:red; border: 1px solid blue;");

Obviously change the style to "display:none" or "display:block" depending on the appropriate privacy condition: user.name === 'John'

References:

Declaring an HTMLElement Typescript

How to set multiple CSS style properties in typescript for an element?

EGC
  • 1,719
  • 1
  • 9
  • 20
0
  1. if you want add id to the element dynamically you can do it this way
<ul class="navbar-nav float-right"  [attr.id]="'test'">
  <li class="nav-item" >
    <a class="nav-link" routerLink="Private">Private</a>
  </li>
</ul>

  1. But I will recommended to you usage of ngIf instead of id like this
<ul class="navbar-nav float-right"  *ngIf="FunctionFromTs()">
 <li class="nav-item" >
   <a class="nav-link" routerLink="Private">Private</a>
 </li>
</ul>

FunctionFromTs() which will return boolean status of visibility

Ashot Aleqsanyan
  • 4,252
  • 1
  • 15
  • 27