简体   繁体   中英

Angular hide and show buttons not working

I have the following requirement that is not working with my current code. I need to hide or show buttons which sit in my app header component based on a users role.

The users role comes from session storage which is being called in a service file.

     setStoreData() {
        const data = JSON.parse(sessionStorage.getItem(`oidc.user:${environment.accessTokenApiUrl}:${environment.clientId}`));
        return data;
      }

I then consume the service in my header component on ngOnit and assign it to a variable

      ngOnInit() {
            this.userRole = this._storeService.setStoreData().profile.role;
      }

Then comes the function to enable or disable my header button

      isDisabledCorporates(): boolean {
        if (
          this.userRole == 'HR Admin' ||
          this.userRole == 'HR Recruiter' ||
          this.userRole == 'HR Manager' ||
          this.userRole == 'Candidate' ||
          this.userRole == 'Operations administrator' ||
          this.userRole == 'Internal Account Manager') {
          return true;
        } else {
          return false;
        }
      }

      isDisabledArchive(): boolean {
        if (  this.userRole == 'HR Recruiter' ||
              this.userRole == 'HR Manager' ||
              this.userRole == 'Candidate' ||
              this.userRole == 'Operations administrator' ||
              this.userRole == 'Internal Account Manager') {
          return true;
        } else {
          return false;
        }
      }

Lastly I have the html code as follows

    <nav *ngIf="userRole">
      <div>
        <div>
          <button class="nav-link-btn" [routerLink]="['/corporate/dashboard']" *ngIf="isDisabledCorporates()"> Corporates </button>
          <button class="nav-link-btn" [routerLink]="['/archive']" *ngIf="isDisabledArchive()"> Archive </button>
        </div>
      </div>
    </nav>

The problem is that the code does not seem to disable the corporate button and my current user is HR Admin. Any ideas why?

This appears to be inverted logic. The *ngIf structural directive will display the element in the DOM if the method returns true. I recommend adding a ! operator.

*ngIf="!isDisabledCorporates()"
*ngIf="!isDisabledArchive()"

You should use ===, and why don't you try first if your function is returning value or not.

isDisabledCorporates(): boolean {

return true; // or try with return false; }

if this works fine then go ahead an try with the complete code and before all that verify what are you getting in this.userRole after ngOnInit() execution. put a debugger otherwise and see how the function execution is happening.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM