Approach needed to assign identical CSS property to various classes that are dynamically created via ngFor in Angular?

I am currently working on writing CSS for dynamically generated classes. I have set up the classes using ngFor as shown below:

<div style="max-height: 450px;" *ngFor="let item of data; let i = index" class="card{{i + 1}}">
.....
</div>

Now, I am in the process of styling these dynamic classes with CSS rules like this:

@media (min-width: 1399px) {
  .card2,
  .card6 {
   padding-left: 0px;
   padding-right: 0px;
  }
  .card3,
  .card7 {
   padding-right: 0px;
  }
}
@media (min-width: 576px) and (max-width: 768px) {
  .card2,
  .card4,
  .card6 {
   padding-left: 0px;
 }
}

As the number of divs may exceed 20, I am looking for a more efficient way to define these CSS rules without having to list each card individually. Is there a shorter method like using card(n+1) {....}?

Answer №1

If you're working with sass or less, you can utilize control directives in your sass code like this:

@for $i from 0 through 20 {
  .card-#{$i} { padding-left: 0px; }
} 

Check out a live example here.

Answer №2

Assign your existing classes as IDs and utilize a shared class for all elements.

class="block" id="block-{{ i }}"

Answer №3

After carefully reviewing your question, I have provided a solution for dynamically inserting classes in my implementation here.

The key is to create a function that will return the name of your desired class.

If you are looking to apply specific CSS styles to each card element incrementally, you can achieve this by using the following code snippet:

card:nth-child(n+1){
  background-color: red;
}

Answer №4

If there isn't a noticeable pattern to follow and sass is not an option, one alternative could be utilizing the [ngStyle] directive. Here's an example:

<div *ngFor="let item of data; let i = index" class="card-{{i + 1 }}" [ngStyle]="calcStyle(item, i)">
.....
</div>

You can define your desired styles in your .ts file by creating a function like this:

calcStyle(item, i){
  if (i==6){
     return {
       'padding-left': '0px;',
       'padding-right': '0px;'
       }
    }
 }

However, I would recommend exploring options beyond setting padding based on the index of each item. Consider utilizing a grid system for better results.

Answer №5

Super simple! Modify the data type of your class attribute to allow for JavaScript instead of just a string, then incorporate concatenation.

<div
  style="max-height: 450px;"
  *ngFor="let item of data; let i = index"
  [class]="'card' + (i + 1)">
  .....
</div>

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

Changing the Title of UI Tabs

I am facing an issue with setting the title in tabs, as the title is appearing behind the background. If I set background: transparent; in the #tabss .ui-tabs-nav class, then my title shows up properly. Otherwise, it gets displayed behind the background. ...

An unexpected error occurred while running ng lint in an Angular project

I've encountered an issue while trying to run ng lint on my Angular project. After migrating from TSLint to ESLint, I'm getting the following error message when running ng lint: An unhandled exception occurred: Invalid lint configuration. Nothing ...

How to Add Multiple Components to app.module.ts in Angular-cli RC 5

I'm currently working on a project using Angular-cli RC5 and I'm facing some challenges creating charts. First, I created a new component called "chart" Then, I created a directive named "line-graph.directive.ts" This is how my folder structur ...

Having trouble with less.modifyVars not functioning properly in Visual Studio?

I attempted to dynamically change the LESS variable using HTML within an AngularJS function. The code worked fine on XAMPP with simple HTML and CSS, but when I transferred it to an enterprise app in Visual Studio, it stopped functioning properly. While the ...

What is the best way to confine the child elements within a parent element using CSS?

Check out my CSS and HTML code here: https://jsfiddle.net/z2cc11yk/ Here's the HTML: <div class="progressbar-container"> <div class="progressbar-text">125%</div> <div class="progressbar-progress" style="background-color: red; wi ...

What is the best way to design a form like this using CSS and potentially incorporating some JavaScript techniques?

In my current design, I have form labels positioned inline to the left of text fields, with each label varying in width. My goal is to align the right edge of the text fields. Here is how the fields currently appear, with the right edge misaligned: Name: ...

Disabling FormArray on-the-fly in Angular

I have a scenario where I need to disable multiple checkboxes in a FormArray when the page loads. Despite my attempts to implement this, it hasn't been successful so far. Can someone provide guidance on how to achieve this? .ts file public myForm: Fo ...

Tips for aligning headings to the left of buttons

Currently working on a webpage but struggling with web design. Here is my HTML code: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link href="https://googledrive.com/host/0B0vEuOxa0lxIajBoRU1UWmdOQjQ/style.css" r ...

Using JQuery, it is possible to search for elements by one specific class while excluding others

Looking for a way to target elements with a specific class, but only if they don't have another class attached to them. Here is an example: <li class="target-class exclude-class"></li> <li class="target-class exclude-class"></li& ...

Displaying the initial element in an NgFor loop in Angular 2

Whenever I click on the "Add row" button, I dynamically generate a row of inputs and dropdowns. Upon clicking another button, the complete data is submitted and displayed in console.log as an array of objects, with each object representing a single row. C ...

I must update a bootstrap class name within multiple layers of divs by referring to the parent class

My code structure is set up like this: <div id="main-parent"> <div class="child2"> <div> child2 </div> </div> <div>child3</div> - - - - <div class="ch ...

Which is the optimal choice: subscribing from within a subscription or incorporating rxjs concat with tap?

After storing data in the backend, I proceed to retrieve all reserved data for that specific item. It is crucial that the data retrieval happens only after the reservation process to ensure its inclusion. Presented with two possible solutions, I am cont ...

Tips on choosing the initial TD elements within a row

Is it possible to create a CSS code that changes the color of the first TD element in each TR row within a table with the class mytable, recursively? Can you provide an example of how this CSS would look? <table class="mytable"> <tr ...

Navigating to a particular div using a click event

I am trying to achieve a scrolling effect on my webpage by clicking a button that will target a specific div with the class "second". Currently, I have implemented this functionality using jQuery but I am curious about how to accomplish the same task using ...

What steps should I take to ensure that flex aligns the inner-divs on the same row?

I have observed that flex can easily align input tags, regular text, and other elements perfectly on a single line with the flex-direction:row; property. However, this alignment seems to get disrupted when one of the elements is a div. For example: <ht ...

Is there a way to use flexbox in a grid to center only a specific tab from MUI?

I am working with an array of tabs and encountering a layout issue. The tabs need to share the available space when there's more than one tab, but when there's only one tab, it should be positioned in the middle of the column. How can I address t ...

Tips for manipulating fixed elements while navigating through the window's content

I am currently working with Materialize CSS (link) and I'm trying to figure out how to move select content while scrolling the page or when the window is scrolling. However, the example code I've implemented doesn't seem to be working. Is th ...

Utilizing @ngrx/router-store in a feature module: A comprehensive guide

The NGRX documentation for Router-Store only showcases an example with .forRoot(). Upon experimenting with .forFeature(), I realized that this static method does not exist. I am interested in defining certain actions and effects to be utilized within my f ...

Exploring Techniques for Adjusting Website to User's Screen Resolution

My website is currently designed for a screen resolution of 1024x768. However, I am aware that when viewed on computers with smaller or larger screen resolutions, the layout starts to distort. Is there a way to make the website adaptable to any user&apos ...

Error: global not declared in the context of web3

I've been attempting to integrate Web3 into my Ionic v4 project for some time now. However, I keep encountering errors when I try to serve the project. Specifically, I receive an error message stating that Reference Error: global is not defined. Cre ...