微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript-如何在Angular中使用CSS相邻兄弟选择器?

当将Angular组件与styleUrl和单独的样式表文件一起使用时,每个CSS选择器都将在输出中作用于其组件.

现在让我们说我要定义一个规则,即当文章后接另一个特定的组件时,后面的一个组件需要一个页边距.在这种情况下,商品卡后跟商品组元素.

标记将如下所示:

<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>

两者都将包含具有特定类的div,您将在以下示例中看到.

我尝试过这样的事情:

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

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

像这样:

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

但是两者都不起作用,因为当Angular对其进行编译时,标记的浏览器输出将如下所示:

<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>

输出的CSS范围如下:

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

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

也许它需要:host-context或:host的某种组合,但是即使那样,我也从来没有将选择器应用于正确的上下文.

那么有没有办法在Angular样式表中使用Adjacent Sibling CSS Selector?

解决方法:

尝试使用view encapsulation.none,这样就不会获得额外的[_ngcontent-c5]

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

@Component({
  selector: 'app-something',
  encapsulation: ViewEncapsulation.None
})

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐