Is there a way to activate components and actions depending on user roles?

Currently, I am developing a frontend application for a project using Angular 4. From the backend, I receive some POST actions that are listed in a file called actions.response.ts:

actions.response.ts

export class actions{
          AGREEMENTS_VIEW :string;
          PROSPECTS_VIEW :string;
          AGREEMENTS_INSERT_UPDATE :string;
          PRODUCTS_INSERT_UPDATE :string;
          PROSPECTS_INSERT_UPDATE :string;
          DOCUMENTS_VIEW :string;
          DOCUMENTS_INSERT_UPDATE :string;
}

My goal is to enable or disable components, inputs, selects, or buttons based on each action (agreements_view, prospects_view, etc). How can I achieve this?

HTTP POST request:

securityActions(): Observable<actions> {
    return this.http.post<actions>(
        `${this.ENDPOINT}/security-actions`,
        null,
    );
}

How I call the POST request within the component:

  securityActions() {
    this.securityService.securityActions().subscribe(
      (res: actions) => {
        this.actionsSecurity = res;
        console.log(res);

      },
      errors => {
        Utils.notifyErrors(errors, this.notificationsService);
      });
  }

I apologize if my question seems basic, but I am new to Angular and feeling a bit overwhelmed!

Answer №1

For the current project I'm working on, we developed a custom permission directive. This directive takes specified conditions and removes tags from the view if they are not met.

Here is an example snippet of the directive:

export class HasPermissionDirective implements OnInit, OnDestroy {
  private permissionSub: Subscription;

  constructor(private templateRef: TemplateRef<any>,
              private viewContainer: ViewContainerRef,
              private authorizationService: AuthorizationService) {
  }

  ngOnInit(): void {
    this.applyPermission();
  }

  @Input()
  set hasPermission(checkedPermissions: Permission[]) {
    // Set the permissions for the directive here
  }

  private applyPermission(): void {
    this.permissionSub = this.authorizationService.checkPermission(/* permissions to be checked */)
      .subscribe(authorized => {
        if (authorized) {
          this.viewContainer.createEmbeddedView(this.templateRef);
        } else {
          this.viewContainer.clear();
        }
      });
  }

  ngOnDestroy(): void {
    this.permissionSub.unsubscribe();
  }
}

Answer №2

To my understanding, it seems like you are looking to control the activation or deactivation of access to a component or button based on certain conditions. This could be related to factors such as user login status, form validation, etc. If you need to deactivate a button, you can achieve this using the [disabled] directive:

<button class="btn btn-lg btn-primary btn-block" type="submit" [disabled]="!registerForm.valid">
    Submit
</button>

For instance, if the form is not valid, the data submission button will be disabled.

For components, you can handle this within routes. You would first need to create a service that implements the CanActivate interface. Here's an example for authentication:

canActivate(): Observable<boolean> {
    return Observable.from(this.user)
      .take(1)
      .map(state => !!state)
      .do(authenticated => {
        if (!authenticated) {
            this.router.navigate(['/login']);
        }
    });
}

Then, in your routes files, specify the rules accordingly. For example, restricting access to the dashboard only when authenticated:

{ path: 'dashboard', component: DashboardComponent, canActivate: [theServiceYouCreated]}

I hope this explanation serves as a helpful guide. Feel free to reach out if you have any questions or if this doesn't align with what you're seeking.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Replace Formik with useFormik to streamline your code

I have implemented Formik/Yup for validation on a page that triggers a GraphQL mutation. The code is functioning as expected: export default function RemoveUserPage() { const [isSubmitted, setIsSubmitted] = useState(false); const [isRemoved ,setIsRemo ...

Discover the magic of transforming user input into live asterisks using Angular2 and TypeScript

Currently I have a unique input field that transforms text into asterisks as the user types: `<h5>Answer</h5><span><a href="#" (click)="plainText(answer.value)">(show) <input type="text" #answer (keyup)="asterisk(answer.value) ...

How should we provide the search query and options when using fuse.js in an Angular application?

Having previously utilized fuse.js in a JavaScript project, I am now navigating the world of Angular. Despite installing the necessary module for fuse.js, I'm encountering difficulties implementing its search functionality within an Angular environmen ...

Angular - Error: Cannot find module 'fs'

I've encountered an issue while trying to incorporate Node's fs module into my Angular application. It seems that the problem lies in the fact that Angular doesn't operate within a node environment. I'm wondering if there's a way ...

The parameters in VueJS are malfunctioning on this webpage

I created my vue in an external file and included it at the bottom of my webpage, but I am encountering issues with its functionality. One specific problem arises when using v-model, resulting in a template error displayed on the page: Error compiling t ...

Perform a calculation where two numbers are multiplied together and the result is added to a third number

I'm just getting started with functional programming and I'm attempting to create a function that multiplies two numbers together and then adds the result to a third number using TypeScript with rambda. My goal is to have a function that takes t ...

Retrieving an image from the image repository

Having issues with Ionic 3, Angular CLI 7, and Angular 5. I'm encountering difficulties in fetching an image from the library. The problem arises when calling getPicture function. The error message reads: “Object(WEBPACK_IMPORTED_MODULE_1__ioni ...

Angular 6 implement a waiting function using the subscribe method

I need to make multiple calls to a service using forEach, where each call depends on the completion of the previous one. The code is as follows: itemDefaultConfiguration.command = (onclick) => { this.createConfiguration(configuration.components); ...

Ways to dynamically update a Vuetify 3 element's placeholder text?

Here is the code snippet from my component.vue file: <template> <v-text-field name="Foo" :label="$t('foo')" type="text" hint="This is a hint" persistent-hint >& ...

The class variable cannot access the Angular Http response returned by the service

I have a Typescript application built with Angular 2. In this application, I need to retrieve Build Artifacts from a Jenkins server using the Jenkins Rest API. The Build Artifact contains a text file that I want to read from. I am making use of Angular&apo ...

Issue encountered when attempting to assign a value to an array property in Angular

Having trouble setting an array property in angular 6 using the following code: this.addupdate.roleids=this.selectedRole; An error is being thrown: ERROR TypeError: Cannot set property 'roleids' of undefined at AccessLevelComponent.pus ...

Is there a way to alter a container component depending on a condition without duplicating its content?

As I work with Component A, which serves as a container, I am faced with the challenge of selecting either ComponentA or ComponentB based on certain conditions without duplicating the content. <ComponentA *ngIf=true> ...Content </ComponentA&g ...

Showing data related to a certain value - what's the best way?

I am currently working on a page where I need to display and edit specific user information at /users/524.json. However, I also want to include the working days from another table on the same page. I have provided most of the code below for reference. Unfo ...

Using the .json method in Angular 7 for handling responses

While attempting to implement the function getProblems to retrieve all problems within its array, I encountered an error message appearing on res.json() stating: Promise is not assignable to parameters of type Problem[]. It seems that the function is ...

I am looking to include both a space and a comma in the State dropdown value in an Angular application

I am facing an issue with my dropdown in Angular 9. When the State is more than one, it displays without any space between them. I want it to show like: Licensed State:ARCA I need like: AR, CA This is the code I have so far: <ng-c ...

Is there a way to verify if a property shares the same value as another item within an object array using ajv?

I am currently working on creating a JSON schema to validate cross references using AJV and TypeScript. Is there a method to verify that a property includes another property from any item within the array (not a specific item in the array)? Both the prop ...

An error occured in angular2: Cannot access the 'title' property of undefined

Here is the code snippet for my custom component: export class MoviedetailComponent implements OnInit { movie:any constructor( private getmovie: GetmovieService, private router: Router, private rout: ActivatedRoute ) { } ngOnInit() { this.r ...

Create a custom component that wraps the Material-UI TextField component and includes default

I have been exploring React and had a question regarding wrapping a component like TextField from mui to add new props along with the existing ones. I attempted to do this but am struggling to figure out how to access the other props. Can anyone help me ...

Why is it necessary to redefine the interface and its class in Typescript after initially defining the interface with implements?

interface Filter { rowAddRow: (treeData:Tree[],id:string,filterType:FilterType) =>Tree[] } class FilterAction implements Filter { // I must redeclare here to ensure the correct type for id rowAddRow(treeData:Tree[], id, filterType):Tree[] { ...