如何在角指令中瞄准组件内的特定元素。
我有一个带有选择器“荧光笔”的组件。此组件具有使用ng-content的内容项目。
有一个带有选择器“荧光笔输入”的指令。
我认为这个指令应该只应用于荧光笔组件中的任何输入,但是它会应用于应用程序中的所有输入--有什么问题吗?
柱塞:https://plnkr.co/edit/4zd31C?p=preview
@Component({
selector: 'highlighter',
template: `
This should be highlighted:
<ng-content></ng-content>
`
})
export class HighlighterComponent {
}
@Directive({
selector: 'highlighter input'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}发布于 2018-01-15 06:14:03
角中的选择器不支持组合子:
- descendant selector (space)
- child selector (>)
- adjacent sibling selector (+)
- general sibling selector (~)因此,字符串中的最后一个不同的选择器获胜,在您的情况下是input。这就是为什么它适用于所有的输入。
另一件事是,投影内容不被认为位于投影到的组件中。因此,即使角支持组合器选择器,选择器highlighter input仍然不能工作。
最简单的解决方案是向输入中添加一个类,如下所示:
<input class="highlighter">并在选择器中针对这个类:
@Component({
selector: 'input.highlighter'发布于 2018-01-16 18:03:26
角只允许指令触发不跨越元素边界的CSS选择器。
发布于 2018-01-14 23:07:18
指令将应用于它声明的模块中的所有选择器。
https://stackoverflow.com/questions/48255016
复制相似问题