簡體   English   中英

如何在 Angular 中使用 CSS Adjacent 兄弟選擇器?

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

當使用帶有 styleUrl 和單獨樣式表文件的 Angular 組件時,每個 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
})

你可以添加類,像這樣:

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

使用:host選擇器來引用“當前”組件。 像這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM