do not proceed with instructions

i designed this directive to handle user permission validation for displaying or hiding menu items on the page

here is my implementation:

 @Directive({
    selector: '[Permission]'
    })
    export class PermissionDirective {

    @Input() AccessName: string;

    constructor(
        private templateRef: TemplateRef<any>,
        private viewContainerRef: ViewContainerRef,
        private permission: PermissionValidate
    ) {
        console.log(this.AccessName)
        this.show();
     }

    show(): void {
        console.log('in d')
        if (this.permission.validateAccessLevel(this.AccessName)) {

            this.viewContainerRef.createEmbeddedView(this.templateRef);

        } else {

            this.viewContainerRef.clear();

        }

    }

}

and here is how I use the directive in HTML:

<li [Permission]='User:Main' class="side-menu-items-item">
    <div class="item-icon">
        <i nz-icon nzType="team" nzTheme="outline"></i>
    </div>
    <div class="item-label">
        <label>{{'DASHBOARD.MENU_ITEM.USER_MANAGER' | translate}}</label>
    </div>
</li>

[Permission]='User:Main'

however, when implemented in shared.module, the directive does not work as expected and does not enter the Directive

What seems to be the issue? How can I go about resolving it? Updated Question:

this is my updated shared.module

 @NgModule({
  declarations: [ShowErrorComponent, PermissionDirective, EmailExistValidationDirective, UsernameValidationDirective],
  imports: [
    CommonModule,
    MaterialModule,
    ZorroModule,
  ],
  exports: [MaterialModule, PermissionDirective, ZorroModule , ShowErrorComponent, EmailExistValidationDirective, UsernameValidationDirective]
})
export class SharedModule {
  static forRoot(): ModuleWithProviders {
    // Ensuring that only the providers from the AppModule are utilized throughout the app.
    return {
      ngModule: SharedModule,
      providers: [ShowErrorComponent, PermissionDirective, EmailExistValidationDirective, UsernameValidationDirective/* Any additional services needed by `SharedModule`. */]
    };
  }
}

Answer №1

It seems like the issue lies in passing a value to the directive attribute Directive="User:Main".

In the documentation provided by Angular, they demonstrate how to implement it in the following way:

@Directive({
    selector: '[appPermission]'
})
export class PermissionDirective {
    constructor(
        private templateRef: TemplateRef<any>,
        private viewContainerRef: ViewContainerRef,
        private permission: PermissionValidate
    ) {
    }

    @Input() set appPermission(accessName: string) {
        if (this.permission.validateAccessLevel(accessName)) {
            this.viewContainerRef.createEmbeddedView(this.templateRef);
        } else {
            this.viewContainerRef.clear();
        }
    }
}

The consumer of the directive expects to bind a true/false condition to [appUnless]. This requires the directive to have an appUnless property decorated with @Input
As Stavm pointed out - this is a structural directive. Therefore, you will need to use the *.

You can then use it like this:

<li *appPermission='"User:Main"' class="side-menu-items-item"></li>

For a working example, you can refer to: https://stackblitz.com/edit/angular-gjewlg

This particular example functions as expected.

Answer №2

It seems like you may have overlooked the fact that you are working with structural directives, meaning you need a template to properly execute your code.

To simplify things, the Angular team introduced a shortcut in the form of a star prefix:

<li *Permission="true">

I've put together a quick demo for you to see how it works:

Check out the demo here!

Answer №3

To start off, as pointed out by @Stavm earlier, the issue lies in using a structural directive. Furthermore, instead of passing parameters, you should be passing a string. The correct way to pass a string is shown below (using double brackets):

*Permission="'User:Main'"

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

What is the best way to locate a specific item within an array of objects, especially when each object has the potential to contain an array of objects of the

I am grappling with the challenge of finding a specific object within an array of objects, where the desired object may be nested within another array of one of the objects. I have experimented with various iterations of forEach loops and recursion method ...

I am having trouble with the browser detection not accurately identifying the browser I am currently using

Currently, I am working on a JavaScript code that will simply display the name of the browser being used to view the web page. Despite me using Safari, none of the navigators seem to recognize it as the current browser. The information displayed in my brow ...

Error encountered: AxiosError - Request unsuccessful with status code 401 in next.js

My current project uses Next.js, and I've implemented an Axios interceptor to catch rejected promises. However, when there is a server-specific error that requires my attention, Next.js displays the error like this: https://i.sstatic.net/HHhD2.png B ...

Switch between adding elements to various div containers

Can we implement a functionality where clicking an anchor tag moves the .item from .region1 to .region2, and then moving it back to .region1 when clicked again? Essentially creating a toggle behavior? <a href="#" class="btn">Click</div> &l ...

Learn the process of uploading an image to Firebase storage from the server side

I'm working on implementing an upload feature that utilizes Firebase storage on the server side. Here is the upload function on the server side: const functions = require("firebase-functions"); const admin = require("firebase-admin&quo ...

Failed to retrieve information using a custom header in the HTTP request

My AngularJS code works well without the header option. $http.get(env.apiURL()+'/banks', { headers: { 'Authorization': 'Bearer '+localStorageService.get('access_token') } }) Here is the request: OP ...

Tips for retrieving items from <ng-template>:

When the loader is set to false, I am trying to access an element by ID that is located inside the <ng-template>. In the subscribe function, after the loader changes to false and my content is rendered, I attempt to access the 'gif-html' el ...

What is the best way to include a text input as the last option in a Select input form field?

I would like to implement a select input feature where users can choose from predefined options, with the added functionality of including a text input field as the last option for users who prefer to enter their own category. How can I achieve this? Curr ...

What is the best method for enhancing Express types?

One of my files is named types/express.d.ts declare namespace Express { export interface Response { respondWith(data: any): Response; } } I also have this code snippet in app.js Express.response.respondWith = function(data) { return this.json( ...

Creating and troubleshooting an Angular 7 project in Visual Studio 2017

After setting up my angular7 project with the ng new my-app command (following the steps at https://angular.io/guide/setup-local), I wanted to continue developing and debugging using Visual Studio 2017 (not Visual Studio Code). When attempting to use Visu ...

Analyzing dates using loops in JavaScript

In order to compare dates using JavaScript, I have written a function: function fulljson (){ var db_data; $.ajax({ url: "http://localhost:8888/auction/offers/5", type: "GET", async: true, ...

Create a distinct number between 0 and X while maintaining a record to avoid repeating values

Recently, I faced a challenge that required me to create a function capable of generating a random number within a specified range from 0 to X. The catch was that the number returned had to be unique, meaning it couldn't repeat numbers that were alrea ...

Error: The Mui Material Breakpoints Theme Cannot Be Located

Hello there! I'm having some trouble placing my code breakpoints, resulting in an error in the output. Can you help me? import { makeStyles } from "@material-ui/styles"; const useStyle = makeStyles((theme)=>({ LogoLg:{ display:&ap ...

incorporating a dynamic parameter into the payload of an AJAX post request

I'm currently working on a function call where I want to extract the value of the variable data and place it in the data section of the function. However, despite my efforts, I haven't been successful so far. In PHP, I am attempting to retrieve t ...

Configuring JsFiddle with Vue and integrating vue-tables-2 - The variable "t" is not defined

Seeking assistance for implementing the vue-tables-2 package and encountering a persistent issue. Despite my efforts to set up a jsfiddle, I keep encountering an error stating "t is undefined" even with a simple implementation. Has anyone faced this specif ...

Partially accessible Angular service within a callback function

I'm currently facing an issue in my Angular simple app related to a factory that is not fully available within a callback function. You can check out a simplified version of the application on this Plunkr link. Here's a snippet of the code: Th ...

Is it possible to showcase the data from three or more PHP files on a single webpage?

I currently have three PHP files: pie.php, bar.php, and line.php. When each file is run individually, it displays a webpage with a pie chart, bar chart, or line graph respectively. However, running all three files opens up separate webpages for each graph. ...

Ways to access JSON data in JavaScript

I'm experiencing difficulty accessing the JSON data provided below. My approach involves utilizing the JavaScript AJAX success function, and when attempting alerts with the following code, $.ajax({ type:'GET', url:myURL, success : function ...

Tips for resolving the error: finding the right loader for handling specific file types in React hooks

data = [{ img: '01d' }, { img: '02d' }] data && data.map((item) => ( <img src={require(`./icons/${item['img']}.svg`).default} /> )) I am facing an issue with the message Error: Module parse failed: U ...

How to identify NaN in JavaScript code?

I am attempting to use JavaScript to determine the number of days in a selected month of a selected year. However, I keep receiving a NaN value as a result. How can I resolve this issue? Thank you. <script> function myFunction() { var month ...