如何在 Angular 指令中定位组件内的特定元素。
我有一个带有选择器“荧光笔”的组件。该组件具有使用 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';
}
}
最佳答案
Angular 中的选择器不支持 combinators :
- descendant selector (space)
- child selector (>)
- adjacent sibling selector (+)
- general sibling selector (~)
因此字符串中最后一个不同的选择器获胜,在您的情况下是 input
。这就是它应用于所有输入的原因。
另一件事是投影内容不被认为位于被投影到的组件内。因此,即使 Angular 支持组合选择器,选择器 highlighter input
仍然不能工作。
最简单的解决方案是像这样向输入添加一个类:
<input class="highlighter">
并在选择器中定位这个类:
@Component({
selector: 'input.highlighter'
关于Angular 4 指令选择器仅针对组件内的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48255016/