简体   繁体   English

具有可选属性的自定义指令的角度CSS选择器

[英]Angular css selector for custom directive with optional attribute

Lets say I created a custom directive who's selector is [myCustomDirective] , this directive has optional input parameter. 可以说我创建了一个自定义指令,其选择器是[myCustomDirective] ,该指令具有可选的输入参数。 So it may be used like: 所以它可以像这样使用:

<div myCustomDirective></div>

or 要么

<div [myCustomDirective]="someBooleanFromController"></div>

Meanwhile, inside my directive controller I add pseudo class to elementRef on which directive is applied. 同时,在指令控制器内部,我将伪类添加到elementRef了指令的elementRef上。

My question is how my css selector for the directive should look like to be applied no matter if I provide optional attribute for directive or not. 我的问题是,无论我是否为指令提供可选属性,指令的css选择器应如何应用。 I tried to use selector like so: 我试图像这样使用选择器:

[myCustomDirective]:pseudoClassName { 
   // ... some css
}

It did the trick when myCustomDirective is used without parameter, but it doesn't work in cases when parameter is provided for myCustomDirective . 当不带参数使用myCustomDirective时,它可以解决问题,但是在为myCustomDirective提供参数的情况下,它不起作用。

I also tried selector like this: 我也试过这样的选择器:

[myCustomDirective="true"]:pseudoClassName { 
   // ... some css
}

But it didn't work 但这没用

Try the below code: 试试下面的代码:

HTML 的HTML

app.component.html app.component.html

<p [appBetterHighlight]="'Yellow'">Highlight with App better directive</p>

CSS 的CSS

style.css style.css

 p[ng-reflect-app-better-highlight] {
    color: blue !important;
 }

Here's how the html in interpreted in browser tool 这是在浏览器工具中解释html的方式

<p _ngcontent-c4="" ng-reflect-app-better-highlight="Yellow" style="">Highlight with 
 App better directive</p>

The best way to add a CSS to a particular custom directive it to access it in CSS like below: 将CSS添加到特定自定义指令的最佳方法是如下所示:

p[ng-reflect-{custom directive name}] { 
    // css here
}

stackblitz demo stackblitz演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM