css - 具有可选属性的自定义指令的角度 css 选择器
问题描述
假设我创建了一个自定义指令,它的选择器是[myCustomDirective]
,该指令具有可选的输入参数。所以它可以像这样使用:
<div myCustomDirective></div>
或者
<div [myCustomDirective]="someBooleanFromController"></div>
同时,在我的指令控制器中,我将伪类添加到elementRef
应用指令的位置。
我的问题是,无论我是否为指令提供可选属性,我的指令的 css 选择器应该如何应用。我尝试像这样使用选择器:
[myCustomDirective]:pseudoClassName {
// ... some css
}
它在myCustomDirective
不带参数使用时起到了作用,但在为 提供参数的情况下不起作用myCustomDirective
。
我也尝试过这样的选择器:
[myCustomDirective="true"]:pseudoClassName {
// ... some css
}
但它没有用
解决方案
试试下面的代码:
HTML
app.component.html
<p [appBetterHighlight]="'Yellow'">Highlight with App better directive</p>
CSS
样式.css
p[ng-reflect-app-better-highlight] {
color: blue !important;
}
这是在浏览器工具中解释 html 的方式
<p _ngcontent-c4="" ng-reflect-app-better-highlight="Yellow" style="">Highlight with
App better directive</p>
将 CSS 添加到特定自定义指令的最佳方法是在 CSS 中访问它,如下所示:
p[ng-reflect-{custom directive name}] {
// css here
}