Tips for retrieving the first true value in an *ngIf statement within an *ngFor loop

I have an array of items that must be shown based on different roles. I am looking for the first item in the array that meets the ngIf condition.

Below is my code snippet:

This is how my Array initially looks:

parentTabList = [ 
        {
            name: 'abc',
            label: 'abc',
            icon : 'question_answer',
            role : ['vend_perm','vend_temp','vend_subs']
        },
        {
            name: 'xyz',
            label: 'xyz',
            icon : 'question_answer',
            role : ['vend_perm','vend_subs']
        }
    ]

This is my Html:

<ng-container *ngFor="let form of parentTabList let i = index">
    <li *ngIf="form.role.includes(userRole)">
        <a (click)="methodName(form)" [ngClass]="{'first-anchor': i === 0}">
            {{form.label}}
        </a>
    </li>
</ng-container>

UserRole is a string value retrieved upon user login.

I also need to apply a ngClass to the anchor tag if it happens to be the first one displayed. (I am new here, so feel free to ask for more clarification).

Answer №1

If you want to find the first element in an array, you can do so by using its index.

However, it seems like what you really want to do is filter the array based on roles and then apply ngClass to the first element from the filtered list.

To achieve this, you can create a method that returns a filtered array based on roles.

In your Template:

 filterParentTabList(parentList: any) {
     return parentList.filter(item => item.role.includes(this.userRole));
 }

In your View:

<ng-container *ngFor="let item of filterParentTabList(parentTabList); let i = index">
    <li>
        <a [ngClass]="{ 'yourClassName': i === 0 }" (click)="yourMethodName(item)">
            {{item.label}}
        </a>
    </li>
</ng-container>

Keep coding away! :)

Answer №2

To implement this functionality, use the following structure. Here, f denotes the initial position in your array.

<ng-container *ngFor="let form of parentTabList; let i = index; let f = first">
    <li *ngIf="f">
        <a (click)="methodName(f)">
            `{{f.label}}`
        </a>
    </li>
</ng-container>

If you need to access other positions within your array, simply follow the pattern mentioned above.

Answer №3

If you want to retrieve the index, you can create a getter in your TypeScript code and use it within your HTML template.

  get firstIndex() {
    return this.parentTabList.indexOf(this.parentTabList.find(({role}) => 
      role.includes(this.userRole)))
  }

Next, utilize this in your HTML:

<ng-container *ngFor="let form of parentTabList let i = index">
    <li *ngIf="form.role.includes(userRole)">
        <a [ngClass]="{redText: firstIndex === i}" (click)="methodName(form)">
            {{form.label}}
        </a>
    </li>
</ng-container>

Check out Demo on StackBlitz Here

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

Continuously building up with the setInterval function

Is it possible to create a 'flash' effect for a list using setInterval in JavaScript? I've noticed that if I leave the page open and return after some time, the setInterval seems to be running every 1 second instead of every 10 seconds. It ...

Executing a setInterval function in NodeJs without prolonging the process's lifespan

To better grasp what I need to do, I simplified the task at hand: we have a lengthy nodejs process with numerous queued async functions, making it impossible to predict when they will finish. Our goal is to create an update process that stores the current ...

Enhance data table by displaying a set number of rows that do not completely fill the table's height

I'm currently attempting to implement a v-data-table with fixed header and footer. However, I've encountered an issue where if I set the table height to be larger than the row height, the table takes on the defined height and the footer ends up b ...

Switch all occurrences of https URLs with <a> using the stencil technology

I am encountering an issue with replacing the answer retrieved from an API and formatting it correctly answerFromAPI = "textword textword textword textword textword.\n\nFeel free to ask me questions from this site:\nhttps://google.com &bso ...

Creating a server that is exclusive to the application in Node.js/npm or altering the response body of outgoing requests

As I work on developing a node app, the need for a server that can be used internally by the app has become apparent. In my attempts to create a server without listening to a port, I have hit a roadblock where further actions seem impossible: let http = ...

Is there an issue with this code? HTML5 canvas

I am attempting to create a mesmerizing animation of a black hole simulation using the canvas element. My goal is to make objects exit the black hole if their distance from its center is greater than the black hole's radius, and to do so at variable s ...

The xModal window will only pop up once, after which a page refresh is required

My modal window opens when a user clicks on a div, but I'm having an issue. The modal window doesn't reopen when I click on the div again. Here is my code: <div onclick="document.getElementById('id01').style.display='block&apos ...

Choose the material and eliminate any gaps

Is there a preferred method for eliminating empty space in Material select/input fields? I am looking to ensure the field width matches the content size. https://i.stack.imgur.com/ZmgKK.png Visit https://material.angular.io/components/select/overview for ...

Sequelize Error: Property 'max' is not defined on the object

There seems to be a problem with my model being undefined. This is how I have set up my code: db.js const fs = require("fs"); const path = require("path"); const Sequelize = require("sequelize"); const basename = path.basename(module.filename); const env ...

Can you explain the distinction between Vue's 'v-on' directive and vue.$on method?

If I have two sibling components set up like this: <div id="root2"> <some-component>First</some-component> <some-component>Second</some-component> </div> ... and these components are coded as follows: Vue.comp ...

Create a left-aligned div that spans the entire width of the screen, adjusting its width based on the screen size and positioning it slightly

I have a parent container with two child elements inside. I want the first child to align to the left side and the second child to align to the right side, but not starting from the exact center point. They should be positioned slightly off-center by -100p ...

What distinguishes a WAV file recorded from a user's microphone versus a WAV file imported from a separate file? Identifying the unique characteristics that may be causing bugs

Currently, I have two methods available for sending a WAV file to the server. Users can either upload the file directly or record it using their microphone. After the files are sent, they undergo a similar processing workflow. The file is uploaded to S3 an ...

Transferring NodeJS information to JavaScript

I am currently working on a web application where the client receives data from a server. The challenge I'm facing is how to pass this data from NodeJS to a Javascript file that is included in an HTML document. Unfortunately, I have not been successfu ...

Instructions on activating the standard scrolling function for a specific DIV element

I'm struggling to achieve a specific scrolling effect on my one-page website. I want the initial section to be displayed as a full page, and when the user scrolls down, it should transition to the next section with a full page scroll. However, once th ...

What are the steps to utilize an Angular component alongside the ui.bootstrap.modal feature in Angular version 1.5?

Looking to incorporate an angular component with ui.bootstrap.modal using angular version 1.5. Here's what I've tried. Component function MyComponentController($uibModalInstance){ var ctrl = this; ctrl.doSomething = function() { // ...

Techniques for capturing Django's output from an Ajax request

I've been trying to utilize Ajax for converting my form data to JSON and sending it to my Django view. However, I'm encountering an issue where after successful processing in the view, I am returning a template response with some context data tha ...

Creating a callback function within its own definition

I need help with my download function that is calling a callback to "downloadCallback". Is it possible to define the downloadCallback function inside the download function itself? If so, how can I achieve this? Below is the implementation of the download ...

Is there a way to maintain scroll position on a dynamically refreshing div?

After searching for hours, I still can't find a solution to my problem. I am using a simple JQuery script to refresh a div and display my PHP output in it. $script = " <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery ...

Ember Component Incorporating Keyboard Input

I recently developed an ember component that features a rectangular block in a green canvas. Everything is working smoothly so far. However, I am facing some challenges with implementing keyboard input commands (A S D W) to navigate the rectangle within t ...

CSS translation animation fails to execute successfully if the parent element is visible

Inquiries similar to this and this have been explored, but do not provide a solution for this particular scenario. The objective is to smoothly slide a menu onto the screen using CSS translation when its parent is displayed. However, the current issue is ...