Try this:
<div
*ngFor="element of elements1; let first = first;"
class="element"
[ngStyle]="first && {'color': 'blue'}">
</div>
This will set the color only for the first div.
Try this:
<div
*ngFor="element of elements1; let first = first;"
class="element"
[ngStyle]="first && {'color': 'blue'}">
</div>
This will set the color only for the first div.
:first-of-type
means “first of type” and not “first that matches the previous bit of the selector”.
The class is irrelevent. The element type is div.
.element {
color: red;
}
.element:first-of-type {
color: blue;
}
<section>
<div class="element">This is the first div in the section</div>
<div class="element">
This is the second div in the section
<div class="element">This is the first div in the div</div>
<div class="element">This is the second div in the div</div>
</div>
<p class="element">This is the first p in the section</p>
<p class="element">This is the second p in the section</p>
</section>
first-of-type will get the element type using the class, so for example if the class is assigned on a p
then the p
should be the first of it’s type to work so if there is any other p
even from another class it will not detect it.
p:first-of-type {color:blue}
.myclass1:first-of-type {color:red}
.myclass2:first-of-type {color:green}
<div>
<div>This text should appear as normal</div>
<p>This text should be blue.</p>
<p class="myclass1">This text should appear red.</p>
<p class="myclass2">This text should appear green.</p>
</div>
check this also:
When we have this part of code:
<div *ngFor="element of elements1" class="element"></div>
<div *ngFor="element of elements2" class="element"></div>
And class Element:
.element {
color:red;
}
.element:first-of-type {
color:blue;
}
And we have two cases:
The first one is when the class element
is global.
In this case just the first element of elements1
will be blue
The second one is when the class “element” is local.
In this case fist elements of both of the arrays will be blue
Why behavior in both cases isn’t the same?
I don’t need another implementation. I want to understand the behavior.
@Student Okay, Quentin’s answer explains the reason. If you have further issues replicate your issue in a stackBlitz or something similar.
Ok, I understand this, but why second case working with another behavior?
@Student — The differences between your two cases are unclear. You should provide a
Yes, you can use first-of-type with classes:
then why the snippet in my answer is not working?
It’s working, the problem is that the type in this case is a paragraph and once it matches the first paragraph, the other rules are not applicable. See this other snippet in which I’m mixing paragraphs and spans:
Thanks that was good to know i’ll change my answer
but still it uses the class only to get the type and then to select the first of that type.