# How to provide role based access to component/element?

It's common requirement of any web application to manage access/visibility of component,element or UI block.

With Vuexy Angular you can easily manage it as we provide built in Role Based JWT Authentication

WARNING

If you are using the strter-kit and want to provide role based access to component/element, you must have implemented JWT and Role based access in Starter-kit. For more details...

To provide role based access to component/element, you need to verify logged-in user role. For that we will use AuthenticationService.

TIP

In full-version refer ecommerce dashboard component ecommerce.component.ts as we've implemented this in it. If you login with Admin credentials, then you can have access to the all dashboard elements and If you login with Client credentials, then you can have limited access to few elements.

To implemented role based access, import AuthenticationService as below in the code and create constructor to access currentUser, isAdmin & isClient.

...
import { AuthenticationService } from 'app/auth/service';
...

@Component({
  selector: 'app-ecommerce',
  templateUrl: './ecommerce.component.html',
  styleUrls: ['./ecommerce.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class EcommerceComponent implements OnInit {
  ...

  /**
   * Constructor
   * @param {AuthenticationService} _authenticationService
   *  ...
   */
  constructor(
    private _authenticationService: AuthenticationService,
    ...
  ) {
    // Get the currentUser, isAdmin and isClient
    this._authenticationService.currentUser.subscribe(x => (this.currentUser = x));
    this.isAdmin = this._authenticationService.isAdmin;
    this.isClient = this._authenticationService.isClient;

    ...
  }

}

Now, in your component HTML file

<div class="row" *ngIf="isAdmin || isClient">
  <!-- Accessible to Admin and Client both -->
</div>
<div class="row" *ngIf="isAdmin">
  <!-- Accessible to Admin only -->
</div>
<div class="row" *ngIf="isClient">
  <!-- Accessible to Client only -->
</div>

Simple! isn't it? Still if you are not clear please refer full-version refer ecommerce dashboard component ecommerce.component.ts as we've implemented this in it.

Last Updated: 6/12/2021, 10:23:39 AM