Creating Class Names Dynamically in Angular 2 Using ngFor Index

Encountering an issue while trying to generate a dynamic class name based on the ngFor loop index in Angular 2. Due to restrictions, I had to use a specific syntax as Angular 2 does not support ngFor and ngIf together on the same element.

Given this setup, how can I dynamically set a class name using the value of index at {{index}}? Although this may not adhere strictly to A2 standards, I included it in the example code to indicate where I aim to insert the value.

<div class="product-detail__variants">
    <template ngFor #variant [ngForOf]="variants" #index="index">
        <div *ngIf="currentVariant == index">
            <div class="product-detail-carousel-{{index}}">

            </div>
        </div>
    </template>
</div>

The variable "variants" stands for an empty array with a specific length, hence "variant" holds no actual value.

"currentVariant" denotes a number that typically begins at 0.

UPDATE: The provided code is accurate. My previous issue stemmed from an unrelated error that I mistakenly associated with this piece of code.

Answer №1

I must admit, your problem is a bit puzzling ;-)

When it comes to assigning classes to specific elements, there are two main approaches:

  • The first method involves using curly brackets like so:

    @Component({
      selector: 'my-app',
      template: `
        <div class="product-detail__variants">
          <template ngFor #variant [ngForOf]="variants" #index="index">
            <div *ngIf="currentVariant == index">
              <div class="product-detail-carousel-{{index}}">
                Test
              </div>
            </div>
          </template>
        </div>
      `,
      styles: [
        '.product-detail-carousel-2 { color: red }'
      ]
    })
    

    In this scenario, the text "Test" will only appear for the third item (with an index of 2) and will be styled in red.

  • Alternatively, you can utilize the ngClass directive as recommended by @Langley:

    import {NgClass} from 'angular2/common';
    
    @Component({
      selector: 'my-app',
      template: `
        <div class="product-detail__variants">
          <template ngFor #variant [ngForOf]="variants" #index="index">
            <div *ngIf="currentVariant == index">
              <div class="product-detail-carousel-{{index}}">
                Test
              </div>
            </div>
          </template>
        </div>
      `,
      styles: [
        '.product-detail-carousel-2 { color: red }'
      ],
      directives: [ NgClass ]
    })
    

    The key difference here is that you'll need to include the NgClass directive within the providers section of your component definition. Once again, "Test" will only be visible for the third element (index 2) and will be displayed in red.

Your statement regarding "The variants array being empty with set length and the variant having no value, while currentVariant defaulting to 0" raises the question of what you expect to see when iterating over an empty array using ngFor...

Hoping this sheds some light on the matter, Thierry

Answer №2

If you are interested in dynamically adding a specific class based on the index, here's a neat way to achieve that. I find this syntax quite intuitive as well. For example, if you want to assign the class last-para to the last paragraph in an array:

<p
  *ngFor="let p of paragraphs; let i = index"
  [class.last-para]="i >= paragraphs.length - 1">
  {{p}}</p>

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

Focusing on the active element in Typescript

I am working on a section marked with the class 'concert-landing-synopsis' and I need to add a class to a different element when this section comes into focus during scrolling. Despite exploring various solutions, the focused variable always seem ...

How to Monitor Store Changes within a Vue File Using Vue.js

I am working with 2 vue files, header.vue and sidebar.vue. Both components are imported into layout.vue. Here are the steps I am following: 1. Initially, when the page loads, I update the store in header.vue with some values inside the created hook. 2. ...

Absence of skins and themes in TinyMCE (Angular)

As per the guidelines provided in the official documentation, I am currently in the process of self-hosting the plugins for TinyMCE by following the step-by-step instructions: 1) Execute npm install --save tinymce. 2) Include the specified lines in angul ...

Choice of product variations as a package

I am currently working on a project and here is the data structure I have set up for options and combinations: https://i.sstatic.net/K2utM.gif Options: "options": [ { "id": "96ce60e9-b09b-4cf6-aeca-83f75af9ef4b", "posit ...

Invoking a function within an HTML file does not result in triggering an alert message

Hello everyone, thank you for taking the time to look at this. I'm attempting to execute a javascript function when I click on the update button. Here is the javascript code: var text2Array = function() { // This function takes the value from the t ...

Ways to resolve issues related to null type checking in TypeScript

I am encountering an issue with a property that can be null in my code. Even though I check for the value not being null and being an array before adding a new value to it, the type checker still considers the value as potentially null. Can anyone shed lig ...

Spin the Three.js camera in a circular motion along the Y-axis

I'm feeling a bit puzzled about this one :S I've written a code that allows my camera to rotate only halfway. I can move the camera along half of a circle using mousemove events, but I actually want it to be able to complete a full rotation :) ...

Sending data using Ajax to the server-side code in ASP.NET

Struggling to successfully pass a series of values through Ajax to a code-behind method in order to insert the data into a database table. However, encountering issues where string variables are being received as empty strings and int variables as 0. The ...

Utilize a variable within an HTML attribute

Currently utilizing Angular and I have the following HTML snippet <input onKeyDown="if(this.value.length==12 && event.keyCode!=8) return false;"/> Is there a way for me to incorporate the variable "myNum" instead of the ...

perform an action if any division element is void of content

Currently, I have a statement that checks if any of the Divs with the ID #Drop are empty. If one is found to be empty, an alert is shown. However, there seems to be an issue where the statement stops working when any div contains content. What I am trying ...

Using AJAX to update content based on selected value in a dropdown menu

My challenge lies in ensuring that a select box retains the selected value from a database entry and triggers an onchange event during form editing or updating. While I have successfully populated the data in the select box based on other selections, I a ...

Prevent legend strike-through on click in Vue Chart.js

Recently, I made the transition from vue 2 to vue 3 on my website and part of that process involved updating vue-chartjs and chartjs too. However, after modifying the legend text of my pie chart using the generateLabels option (as seen below), the striket ...

When using jQuery with a large selectbox, you may encounter the error message: "Uncaught RangeError: Maximum

My select box works fine in IE and Mozilla, but throws an uncaught rangeError in Chrome when choosing the "Others" option to display a second select box with over 10k options. How can I diagnose and resolve this issue? <!DOCTYPE html> ...

Failure to Present Outcome on Screen

Seeking assistance! I attempted to create a mini loan eligibility web app using JavaScript, but encountered an issue where the displayed result did not match the expected outcome upon clicking the eligibility button. Here is the HTML and JavaScript Code I ...

Utilizing AJAX within a Rails application to dynamically alter a database field without the need for a traditional form

I am facing a scenario where I have implemented a table with certain rows structured as follows: <div class="row chord-table-row" id= <%= "chord-#{chord.id}" %>> <div class="small-1 columns"><%= chord.id %></div> < ...

Extending an interface in TypeScript does not permit the overriding of properties

While working with Typescript, I encountered an issue where I couldn't make a property not required when overwriting it. I have defined two interfaces: interface IField { label: string; model: string; placeholder? ...

I'm having trouble importing sqlite3 and knex-js into my Electron React application

Whenever I try to import sqlite3 to test my database connection, I encounter an error. Upon inspecting the development tools, I came across the following error message: Uncaught ReferenceError: require is not defined at Object.path (external "path ...

Why is the mappable Observable lost after using Angular 5's HttpClient?

Why is Angular 5 httpclient causing me to lose the observable after mapping? Am I overlooking something crucial in my code? The following is my code snippet: getRepos(org:string):Observable<any>{ let params = new HttpParams().set('org&ap ...

Difficulty with Nuxt + Vuex: Retrieving data from state using getter

Can anyone assist me with this issue? I am having trouble with my getters in Vuex not recognizing the state. Here is the code snippet: https://codesandbox.io/s/crazy-moon-35fiz?file=/store/user.js user.js: export const state = () => ({ user: { is ...

What is the best way to reduce the file size of a group of PNG images for

For my game character, I have a collection of PNG files including stand.png, run1.png, run2.png. To display a series of actions on the JavaScript canvas, I need to load these images. However, the size of each .png file adds up quickly – for example, it ...