The routerLink directive seems to be absent from the HTML code in Angular 8

Objective: the aim is to dynamically generate a list using two arrays.

https://i.sstatic.net/mixRV.png

Email option is manually created https://i.sstatic.net/mi23u.png

Array Routes:

[[{pri_access:"Administracion/Usuarios",pri_name:"Usuarios"},{pri_access:"Administracion/Privilegios",pri_name:"Privilegios"},{pri_access:"Administracion/Rol",pri_name:"Rol"}],[{pri_access:"Reporte/Ventas",pri_name:"Ganancias"}]]

https://i.sstatic.net/3o55g.png

Array Group:

["ADMINISTRACION","REPORTE"]

https://i.sstatic.net/bw29u.png

The group and route array are of equal size. The dynamic list creation process is as follows https://i.sstatic.net/QjqhV.png

 import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@common/http';
import {PrivilegesService} from '../../SisVentas/service/Privileges/privileges.service';

@Component({
    selector: 'app-sidebar',
    templateUrl: './sidebar.component.html',
    styleUrls: ['./sidebar.component.sass']
})
export class SidebarComponent implements OnInit {
    userName: string = btoa(localStorage.getItem('USER_NAME'));
    rolName: string = btoa(localStorage.getItem('NAME_ROL'));
    tokenUser: string = localStorage.getItem('TOKEN_USER');
    privileges: any[] = [];
    tempPrivileges: any[] = [];
    tempKeys: any[] = [];
    
    privilegesGroup: any[] = [];
    privilegesRoute: any[] = [];

    constructor(
        private httpClient: HttpClient,
        private privilege: PrivilegesService,
    ) { }

    ngOnInit() {
        if (this.tokenUser) {
            this.getPrivilegesByRol();
        }
    }

    getPrivilegesByRol() {
        const idRol = localStorage.getItem('ROL');

        this.privilege.getPrivilegesByRol(idRol).subscribe(
            resp => {
                this.tempPrivileges.push(resp);

                for (let i = 0; i < this.tempPrivileges.length; i++) {
                    for (let j = i; j < this.tempPrivileges[i].length; j++) {
                        if (!this.privileges.hasOwnProperty(this.tempPrivileges[i][j].pri_group)) {
                            this.privileges[this.tempPrivileges[i][j].pri_group] = [];
                        }
                        this.privileges[this.tempPrivileges[i][j].pri_group].push({
                            pri_access: this.tempPrivileges[i][j].pri_acces,
                            pri_name: this.tempPrivileges[i][j].pri_nombre,
                        });
                    }
                }

                for (let key in this.privileges) {
                    this.privilegesGroup.push(key);
                    this.privilegesRoute.push(this.privileges[key]);
                }

                console.log(JSON.stringify(this.privilegesRoute));
                console.log(JSON.stringify(this.privilegesGroup));
            },
            error => {
                console.error(error);
            }
        );
    }
}

HTML

<div>
    <!-- Left Sidebar -->
    <aside id="leftsidebar" class="sidebar">
        <div class="menu">
            <ul class="list">
                <li class="sidebar-user-panel">
                    <div class="user-panel">
                        <div class=" image">
                            <img src="assets/images/usrbig.jpg" class="img-circle user-img-circle" alt="User Image" />
                        </div>
                    </div>
                    <div class="profile-usertitle">
                        <div class="sidebar-userpic-name"> {{this.userName}} </div>
                        <div class="profile-usertitle-job "> {{this.rolName}} </div>
                    </div>
                </li>

                <li routerLinkActive="active" *ngFor="let group of privilegesGroup; let a = index" >
                    <a href="#" onClick="return false;" class="menu-toggle">
                        <i class="fas fa-tag"></i>
                        <span>{{group}}</span>
                    </a>
                    <ul class="ml-menu">
                        <li routerLinkActive="active" *ngFor="let route of privilegesRoute[a]">
                            <a routerLink="{{route.pri_access}}">{{route.pri_name}}</a>
                        </li>
                    </ul>
                </li>

                <li routerLinkActive="active">
                    <a href="#" onClick="return false;" class="menu-toggle">
                        <i class="fas fa-mail-bulk"></i>
                        <span>Email</span>
                    </a>
                    <ul class="ml-menu">
                        <li routerLinkActive="active">
                            <a routerLink="email/inbox">Inbox</a>
                        </li>
                        <li routerLinkActive="active">
                            <a routerLink="email/compose">Compose</a>
                        </li>
                        <li routerLinkActive="active">
                            <a routerLink="email/read-mail">Read Email</a>
                        </li>
                    </ul>
                </li>

            </ul>
        </div>
    </aside>
</div>

ISSUE: Upon inspection of the HTML code, it appears that routerLink is not being generated for the dynamically created list items, unlike the statically created email option. What could be causing this discrepancy?

https://i.sstatic.net/Hjsrb.png

Answer №1

It is recommended to eliminate this section from the html code

Therefore, consider using the following structure:

 <li *ngFor="let group of privilegesGroup; let i = index">  
      .
      .
      .
      <ul>
        <li *ngFor="let route of privilegesRoute[i]">
           <a .... >
        </li>  
      </ul>

   </li>

Answer №2

Consider Using:

If you are utilizing a variable for the router link like

[routerLink]="link" or [routerLink]="['/page1']"
, it may not bind the routerLink attribute to the element. However, if you directly assign a string to the routerLink such as routerLink="page1", it will successfully bind the routerLink attribute to the element. Both methods should still allow routing to function properly.

//app.component.ts
public routerLinks = ["page1", "page2"];

//app.component.html
<div *ngFor="let link of routerLinks">
  <a [routerLink]="link">{{link}}</a>
</div>

Check out this example on StackBlitz: https://stackblitz.com/edit/angular-ivy-onf2ct?file=src/app/app.component.html

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

The functionality of Silex Middleware Authentication varies depending on whether it is being used in Postman or

As a developer with limited experience in back-end development, I have encountered a real problem despite my best efforts. I am currently using Silex as a simple backend for an Angular 2 App. I have implemented a middleware that checks whether the user ha ...

Customizing the hover behavior of a div element without causing displacement of surrounding elements

I am facing an issue where the descriptions in my list of 100 items are longer than the width of the div, causing the text to be cut off. I want to display the full description on hover without affecting the layout of other items. Currently, when I hover o ...

I need to retrieve an item by its ID and then proceed to navigate to the edit form located in a

In my Angular application, I have a service that uses HttpClient to interact with the backend. There are two components involved: trucks and edit-truck. The edit-truck component is responsible for save and update operations. However, when clicking the edit ...

Making a quick stop in Istanbul and NYC to collect a few important files

Setting up Istanbul/Nyc/Mocha for test coverage in my project has been a bit of a challenge. While I was successful in running Nyc, I noticed that not all the .ts files in my project were being picked up for test coverage. When I execute npm run coverag ...

Is it necessary to declare variables in the component's ts file if they are only used in the template in Angular 2

Here is an example where the input is hidden initially and becomes visible when the user clicks a button. The question arises whether the variable showInput should be declared in the component's typescript file. @Component({ selector: 'exampl ...

is there a way to modify the background color of a div element by comparing values in javascript?

Is there a way to dynamically update the background color of a div element within a table based on values stored in a json array from a database? ...

Navigating the complexities of generic types in Typescript involves understanding how to work

Having an issue with my React + TypeScript application. I am trying to write a function to filter some data: function matchesFilter(element: T, filter: Filters) { const { name, options } = filter; return options.filter(selected => select ...

Arrange the array based on the order of the enumeration rather than its values

Looking to create an Array of objects with enum properties. export enum MyEnum { FIXTERM1W = 'FIXTERM_1W', FIXTERM2W = 'FIXTERM_2W', FIXTERM1M = 'FIXTERM_1M', FIXTERM2M = 'FIXTERM_2M', FIXTERM3M = 'FIX ...

Tips for transferring information within a Material 2 dialog in Angular 2 from one component to another

While working with a Material 2 dialog, I have managed to retrieve data upon dialog close successfully. However, I am facing difficulties in finding a solution to pass data to the dialog using @Input. import {Component} from '@angular/core'; im ...

What is the process for generating the configuration files (tsconfig.json, typings.json, package.json)?

I have the ability to duplicate these files from the https://angular.io/guide/quickstart. However, I am eager to learn more about these specific files. Is it possible to create them manually? Where can I find additional information about these files? ...

Is there a way to remove a specific item (identified by its ID) from an array with just a

As a newcomer to Angular 8, I am seeking assistance with deleting an item from an array using (click)="deleteEmployee(el.id)". I attempted to use splice but encountered an error. Below is the code in Component.ts: employee: Employe; id: number; _e ...

Obtaining an array of objects through the reduction of another array

Currently, my goal is to extract an array of objects from another array. Let's say I have an array consisting of strings: const strArr = ["Some", "Thing"]; The task at hand is to create a new Array containing 2 objects for each st ...

​Troubleshooting findOneAndUpdate in Next.js without using instances of the class - still no success

After successfully connecting to my MongoDB database and logging the confirmation, I attempted to use the updateUser function that incorporates findOneAndUpdate from Mongoose. Unfortunately, I ran into the following errors: Error: _models_user_model__WEBPA ...

Is the select attribute in Angular2 limited to only working on textarea elements?

As a newcomer to Angular, I have been using the code below to capture the selected text within a textarea: <textarea (select)="view(textarea.selectionStart, textarea.selectEnd)" #textarea>Hello World</textarea> While this method works fine wi ...

Importing a JavaScript file into an Angular 2 application

Currently, I'm in the process of developing an angular2 application using TypeScript. The Situation: Within my project, there exists a module named plugin-map.ts which is structured as follows: import { Type } from '@angular/core'; impor ...

Discrepancies in output between grunt-ts and tsc

Currently, I have set up a tsconfig.json file in combination with grunt-ts for the following grunt task: ts: { default: { tsconfig: true } Here is the content of the tsconfig.json file: { "compilerOptions": { "target": "es5", "module ...

The Angular application in production is linked to a local Express server rather than the intended production server

Revision 2 Upon further experimentation, I discovered that the site was linking to the Express server on my development computer. When I execute node ./bin/www on the dev machine, the AWS site interfaces with it smoothly and operates without any issues. ...

Exploring the contents of JSON data using json-server

In my database file db.json, I have the following data: { "cases":{ "TotalCount":1, "StartingPageNumber":1, "Data":[ { "Id":1, "CaseNumber":& ...

Retrieve indexedDb quota storage data

I attempted the code below to retrieve indexedDb quota storage information navigator.webkitTemporaryStorage.queryUsageAndQuota ( function(usedBytes, grantedBytes) { console.log('we are using ', usedBytes, ' of ', grantedBytes, & ...

Solid Start is having difficulty executing the Create Effect feature

The function getName is successfully retrieving the name of the person with id 1 from the database, but there seems to be an issue as this code is not logging anything to the console, not even the debug console.log("running"): import { Database } from &apo ...