How can I retrieve the attribute values of a list item from ElementRef while creating an angular directive in Angular 5?

I am currently working on optimizing the HTML structure of my navbar, which contains a list of links. To achieve this, I have created a simple angular directive called 'authorize' as illustrated in the HTML snippet below. However, my challenge lies in ensuring that the Directive can access the value of the [routerLink] attribute of each li item in the list.

Below is the snippet of my navbar HTML with the 'authorize' attribute added at the top level of the list.

  <ul class="nav navbar-nav" authorize>
    <li [routerLinkActive]="['active']">
      <a [routerLink]="['/dashboard']" auth>Dashboard</a>
    </li>
    <li [routerLinkActive]="['active']">
      <a [routerLink]="['/research']" auth>Research</a>
    </li>
    <li [routerLinkActive]="['active']">
      <a [routerLink]="['/profile']" auth>Profile</a>
    </li>
    <li [routerLinkActive]="['active']">
      <a [routerLink]="['/users']" auth>Users</a>
    </li>
    <li [routerLinkActive]="['active']">
      <a [routerLink]="['/todo']" auth>Todo-List-App</a>
    </li>
  </ul>

My goal is for the directive to extract the routerLink value of each link and pass it on to this.routerGuard.permissionApproved(). However, I have encountered difficulties in retrieving these values from ElementRef.

@Directive({
  selector: '[authorize]'
})
export class AuthorizationDirective implements OnInit {
  private el;

  constructor(private ref: ElementRef,
    private routerGuard: RouteGuard,
    private renderer: Renderer) {
    this.el = this.ref.nativeElement;

  }
  ngOnInit() {
    /*  Is there away to get a list of the [routerLink] values here?
        let links = this.el.getAttribute('href')  <- this returns null

        I want to iterate through a list of routerLink values and call a method in my RouteGuard class. 
        
        links.forEach(link=>{
          this.routerGuard.permissionApproved(link);
        });
        */
  }
}

Answer №1

Unsightly demonstration occurring within the ngOnInit lifecycle hook

Array.from(this.el.children).forEach((li: Element) => {
  const link = li.firstElementChild.getAttribute('routerLink');
  if (link) {
    this.routerGuard.checkLinkPermission(link);
  }
});

Modify your link structure to no longer require binding (router functionality will remain intact):

<li [routerLinkActive]="['active']">
  <a routerLink="/dashboard" auth>Dashboard</a>
</li>

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

Creating a specialized TypeScript interface by extending a generic one

Create a customized interface using TypeScript that inherits from a generic interface by excluding the first parameter from all functions. Starting with the following generic interface: interface GenericRepository { insertOne<E>(entity: Type<E& ...

Can someone explain how to create a Function type in Typescript that enforces specific parameters?

Encountering an issue with combineReducers not being strict enough raises uncertainty about how to approach it: interface Action { type: any; } type Reducer<S> = (state: S, action: Action) => S; const reducer: Reducer<string> = (state: ...

Angular's custom reactive form validator fails to function as intended

Struggling to incorporate a customized angular validator to check for date ranges. The validator is functioning correctly and throwing a validation error. However, the issue lies in the fact that nothing is being displayed on the client side - there are n ...

Encountering Errors when Transitioning a Standard React Component to TypeScript

I am currently in the process of migrating https://github.com/catalinmiron/react-typical to TypeScript. However, I am encountering some challenges. Below is a screenshot depicting the errors in VSCode: https://i.sstatic.net/IKZK2.png Here is the same co ...

Unresolved HTTP header problem with Angular 4 and Siteminder

Struggling with integrating Siteminder authentication for my nodejs/angular 4 web application has been a challenge for me over the past few weeks. On the server side (node), my code looks like this: app.get('*', function(req, res) { //read Si ...

How can I incorporate multiple quality sources into a flowplayer using Angular?

Is there a way to add multiple sources with different qualities like 1080p, 720p etc.? Thank you in advance. flowplayer('#my_player', { src: '../assets/videos/video_1080p.mp4', // title: 'This is just demo&apo ...

Efficient Loading and Smooth Scrolling with Angular2 (version 7)

I'm struggling to display a component upon the initial page load using lazy loading, where the content is only loaded when it's in view. For instance: - With 10 components on the page, I aim to show/scroll to component number 7 when the page lo ...

Two paths for a single Angular component

Is it feasible to create two distinct routes that reference one component? Consider the following scenario: { path: 'login', component: LoginComponent }, { path: 'user/:id/login', component: LoginComponent } I'm inquiring about t ...

The Angular Material Calendar is always designed to highlight the current date and keep focus on today's day

When I click on a date in the Angular Material Calendar, the tile for today's date is always highlighted. This occurs even if the selected date is in a different month. Do you think this behavior is a bug or a feature? I personally believe it is a fe ...

Lazy-loaded modules in Angular that contain services provided within the module

Currently, I am facing a challenge with lazy-loaded modules and services that are provided in these modules. My folder structure looks like this: app -> featureModule1 (lazy loaded) -> featureModule2 (lazy loaded) -->services --->servi ...

Indeed, conditional validation is essential

I have encountered an issue with my schema validation where I am trying to validate one field based on another. For example, if the carType is "SUV", then the maximum number of passengers should be 6; otherwise, it should be 4. However, despite setting u ...

Troubleshooting a MutationObserver issue in Angular Universal

I recently tried integrating Angular Universal with SSR into my current project. Even though I followed the provided tutorial, everything seemed to be working fine until I attempted to run the project. Upon executing npm run dev:ssr, I received a "Compil ...

Changing a password on Firebase using Angular 5

I am in the process of developing a settings feature for user accounts on an application I've been working on. One key functionality I want to include is the ability for users to update their password directly from the account settings page. To enable ...

What is preventing Apollo from achieving full transformation?

I have been struggling with an issue involving Apollo mutation for the past 2 days. Whenever I call a mutation on Angular Apollo generated code and subscribe to it, the subscription never completes. I am expecting a result from the server, but nothing is ...

I am currently facing a problem with the PrimeNG calendar feature that is causing issues with setting the minimum date for December and disabling the minimum year

click here to view image The PrimeNG calendar component is presenting a challenge with the minimum date setting for December 2nd to 31st. It seems to be malfunctioning, causing the minimum year to become disabled. Additionally, when the maxdate is set to ...

What causes the variation in Http Post Response between the Console and Network response tab?

Currently, I am tackling an issue in angular2 related to HTTP post response. The problem arises when my endpoint is expected to return a boolean value. Interestingly, the response appears correctly in Chrome's Network response tab; however, upon loggi ...

Trouble with a third-party library component not functioning properly on the server side in a Next.js environment

I've encountered a puzzling issue lately in my work. Recently, I started using the new NextJS v13 with React server components. I'm integrating it into a project that depends on a small private third-party library I created and shared among mul ...

The Angular language service is experiencing difficulties in VS Code when it comes to newly created components using the CLI

I am currently facing an issue with the angular language service in an older project that already has a few components created. The problem arises when trying to generate NEW components using the CLI. For instance, a new component generated today: https:/ ...

The enum cannot be assigned a type of 'string | null'

Within my ProductGender enum, I have: enum ProductGender { Men, Women, } In my getProducts service: public getProducts( gender: ProductGender, category: ProductCategory ): Observable<IProductInterface[]> { return this.httpPro ...

Creating dynamic forms in Angular with partial dynamicity

I'm working on streamlining the process of creating forms using AngularJS. My end goal is to be able to simply write something like: <form> <field-div label="Name"> <field which="form.name"></field> </field-div> ...