Ren*_*der 7 html javascript css angular
当使用带有 styleUrl 和单独样式表文件的 Angular 组件时,每个 CSS 选择器都将在输出中限定于它的组件。
现在假设我想定义一个规则,当一篇文章后面跟着另一个特定组件时,后面的组件需要一个 margin-top。在这种情况下,当文章卡片后跟文章组元素时。
标记将是这样的:
<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>
Run Code Online (Sandbox Code Playgroud)
两者都将包含一个具有特定类的 div,您将在以下示例中看到。
我试过这样的事情:
[article-card] + [article-group] {
margin-top: 20px;
}
article-card + article-group {
margin-top: 20px;
}
Run Code Online (Sandbox Code Playgroud)
像这样:
.article-card + .article-group {
margin-top: 20px;
}
Run Code Online (Sandbox Code Playgroud)
但是两者都不起作用,因为当 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>
Run Code Online (Sandbox Code Playgroud)
输出 CSS 的范围如下:
[article-card][_ngcontent-c5]+ [article-group][_ngcontent-c5] {
margin-top: 30px;
}
article-card[_ngcontent-c5] + article-group[_ngcontent-c5] {
margin-top: 30px;
}
Run Code Online (Sandbox Code Playgroud)
也许它需要 :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
})
Run Code Online (Sandbox Code Playgroud)