[英]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.