Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the CSS Adjacent sibling selector in Angular?

When using Angular components with styleUrl and separate stylesheet files, every CSS selector will be scoped to it's component in the output.

Now let's say I want to define a rule, that when a article is followed by another specific component, the later one needs a margin-top. In this case, when a article-card is followed by a article-group element.

The markup would be something like this:

<article-group
    [topArticlesOnly]="true"
    [articles]="homepage.top | slice:0:6">
</article-group>
<article-card
    *ngFor="let article of homepage.top | slice:0:6"
    [article]="article">
</article-card>

Both will contain a div with a specific class you'll see in the following examples.

I tried something like this:

[article-card] + [article-group] {
    margin-top: 20px;
}

article-card + article-group {
    margin-top: 20px;
}

And like this:

.article-card + .article-group {
    margin-top: 20px;
}

But both doesn't work because the browser output of the markup will be like this when Angular compiles it:

<div _ngcontent-c3="">
    <article-card _ngcontent-c3="" _nghost-c4="" ng-reflect-article="[object Object]" ng-reflect-show-image-only="true">
        <article _ngcontent-c4="" class="article-card article-card--top-article article-card--image-only" ng-reflect-klass="article-card"
            ng-reflect-ng-class="[object Object]">
        </article>
    </article-card>
    <article-group _ngcontent-c3="" _nghost-c5="" ng-reflect-articles="[object Object],[object Object" ng-reflect-top-articles-only="true">
        <div _ngcontent-c5="" class="article-group article-group--top">

        </div>
    </article-group>
</div>

And the outputting CSS scoped like this:

[article-card][_ngcontent-c5]+ [article-group][_ngcontent-c5] {
    margin-top: 30px;
}

article-card[_ngcontent-c5] + article-group[_ngcontent-c5] {
    margin-top: 30px;
}

Maybe it needs some combination of :host-context or :host, but even then I never got my selectors to apply to the correct context.

So is there a way to use the Adjacent Sibling CSS Selector in Angular stylesheets?

like image 846
René Stalder Avatar asked Jul 13 '17 11:07

René Stalder


1 Answers

Try using view encapsulation.none so you don't get those extra [_ngcontent-c5]

import {
  Component, ViewEncapsulation
} from '@angular/core';

@Component({
  selector: 'app-something',
  encapsulation: ViewEncapsulation.None
})
like image 200
seescode Avatar answered Sep 24 '22 16:09

seescode