Disable button based on user role

Hi @sandeep.viswanatha

You could do this via e.g. a service which could look like this:

import { DOCUMENT } from '@angular/common';
import { Inject, Injectable } from '@angular/core';
import { UserService } from '@c8y/client';
import { AppStateService } from '@c8y/ngx-components';
import { filter, first, map } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class StylesheetService {
  private readonly roleToCheck = 'ROLE_ALARM_ADMIN';
  private readonly cssToAdd = `
    .btn-primary {
      background-color: red !important;
    }
  `;

  constructor(
    @Inject(DOCUMENT) private document: Document,
    private appState: AppStateService,
    private userService: UserService
  ) {
    this.appState.currentUser
      .pipe(
        // ensure user is logged in
        filter(user => !!user),
        // check user permissions
        map(user => this.userService.hasRole(user, this.roleToCheck)),
        // only if role is not present go on
        filter(hasPermission => !hasPermission),
        // only need to add this once
        first()
      )
      .subscribe(() => {
        const styleTag = this.document.createElement('style');
        styleTag.setAttribute('type', 'text/css');
        styleTag.appendChild(document.createTextNode(this.cssToAdd));
        document.head.appendChild(styleTag);
      });
  }
}

You would have to adjust the roleToCheck and cssToAdd attributes according to your requirements.
To instantiate the service on application startup, you could inject it via dependency injection in the constructor of one of your modules.

Regards,
Tristan

2 Likes