Austin
Austin

Reputation: 203

Alternate div styles within separate components Angular2

I'm trying to apply a striped look to a few divs. My structure is below. Each component is a new instance that is being rendered in an ngFor loop, like this:

<div *ngFor="let data of dataSet>
  <component1 [data]="data"></component1>
</div>

Rendered HTML

<component1>
  <div>
    <div class="style-this-div">
      some content
    </div>
  </div>
</component1>

<component1>
  <div>
    <div class="style-this-div">
      some content
    </div>
  </div>
</component1>

<component1>
  <div>
    <div class="style-this-div">
      some content
    </div>
  </div>
</component1>

Here is what I have tried:

CSS

  div[class^="style-this-div"]:nth-of-type(odd) {background-color: #efeeee;}
  div[class^="style-this-div"]:nth-of-type(even) {background-color: #efeeee;}

  .style-this-div:nth-child(odd) {background-color: #efeeee;}
  .style-this-div:nth-child(even) {background-color: #efeeee;}

When I use the odd selectors, the gray background color is applied to all of them. I'm trying to get them to alternate colors. What can I do? Thanks!

Upvotes: 1

Views: 865

Answers (2)

blecaf
blecaf

Reputation: 1645

Add a class to the component container like i did below. ANd use the "nth-child" odd and even

.component1:nth-child(odd)  .style-this-div{
  background: red;
}
.component1:nth-child(even) .style-this-div{
  background: yellow;
}
<component1 class="component1">
  <div>
    <div class="style-this-div">
      some content
    </div>
  </div>
</component1>

<component1 class="component1">
  <div>
    <div class="style-this-div">
      some content
    </div>
  </div>
</component1>

<component1 class="component1">
  <div>
    <div class="style-this-div">
      some content
    </div>
  </div>
  </component1>

Upvotes: 2

alcoven
alcoven

Reputation: 321

You'll need to wrap your content in a div with an ID of component1, component2, etc... and Class of component. The reason the nth-child isn't working is because it's looking for the odd ".style-this-div" in each component and not in the document.This way we target the first component class of it's kind and style the div inside.

If you can't change the structure just add the class of .component to your top level element and the css below should still work.

Let me know if you have questions.

HTML

<div id="component1" class="component">
  <div>
    <div class="style-this-div">
      some content
    </div>
  </div>
</div>

<div id="component2" class="component">
  <div>
    <div class="style-this-div">
      some content
    </div>
  </div>
</div>

CSS

  .component:nth-child(odd) .style-this-div {background-color: #efeeee;}
  .component:nth-child(even) .style-this-div {background-color: #fff;}

Codepen Here

Upvotes: 1

Related Questions