【问题标题】:How do I use the CSS Adjacent sibling selector in Angular?如何在 Angular 中使用 CSS 相邻兄弟选择器?
【发布时间】:2017-12-18 03:36:51
【问题描述】:

当使用带有 styleUrl 和单独样式表文件的 Angular 组件时,每个 CSS 选择器都将在输出中限定为它的组件。

现在假设我想定义一个规则,当一篇文章后面跟着另一个特定组件时,后面的需要一个页边距顶部。在这种情况下,当 article-card 后跟 article-group 元素时。

标记将是这样的:

<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 样式表中使用相邻兄弟 CSS 选择器?

【问题讨论】:

    标签: javascript html css angular


    【解决方案1】:

    尝试使用 view encapsulation.none 这样你就不会得到那些额外的 [_ngcontent-c5]

    import {
      Component, ViewEncapsulation
    } from '@angular/core';
    
    @Component({
      selector: 'app-something',
      encapsulation: ViewEncapsulation.None
    })
    

    【讨论】:

    • 这种方法有什么缺点吗?
    • 默认情况下,angular 正在模拟 shadow dom,因此组件中的所有样式都不会泄漏到提供封装的其他地方。但根据具体情况,您可能希望将其关闭。
    • 我暂时接受这个答案,因为它似乎是我确切问题的唯一解决方案。
    【解决方案2】:

    你能像这样添加类吗:

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

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

    【讨论】:

    • 这不是构建组件的正确方式。在组件内部的一个地方使用类的全部好处都将丢失。
    【解决方案3】:

    使用:host 选择器来引用“当前”组件。 像这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-30
      • 1970-01-01
      • 2012-03-08
      • 2016-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多