Sur*_*gar 10 directive selector angular
如何在Angular Directive中定位组件内的特定元素.
我有一个带选择器"highlighter"的组件.该组件具有使用ng-content的内容项目.
有一个选择器"荧光笔输入"的指令.
我相信这个指令应该仅应用于突出显示器组件内部的任何输入,但它应用于应用程序中的所有输入 - 这是错误的吗?
Plunker: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';
}
}
Run Code Online (Sandbox Code Playgroud)
Angular 中的选择器不支持组合器:
- descendant selector (space)
- child selector (>)
- adjacent sibling selector (+)
- general sibling selector (~)
Run Code Online (Sandbox Code Playgroud)
所以字符串中最后一个不同的选择器获胜,这就是input你的情况。这就是它应用于所有输入的原因。
另一件事是投影内容不被认为位于被投影到的组件内。所以即使 Angular 支持组合器选择器,选择器highlighter input仍然不应该工作。
最简单的解决方案是向输入添加一个类,如下所示:
<input class="highlighter">
Run Code Online (Sandbox Code Playgroud)
并在选择器中定位此类:
@Component({
selector: 'input.highlighter'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2765 次 |
| 最近记录: |