Angular 4 指令选择器仅针对组件内的元素
Angular 4 Directive selector to target an element inside a component only
如何在 Angular 指令中定位组件内的特定元素。
我有一个带有选择器 "highlighter" 的组件。该组件具有使用 ng-content 的内容项目。
有一个带有选择器 "highlighter input" 的指令。
我相信该指令应该只应用于荧光笔组件内的任何输入,但它应用于应用程序中的所有输入 - 怎么了?
笨蛋: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
仍然不能工作。
最简单的解决方案是像这样向输入添加 class:
<input class="highlighter">
并在选择器中定位此 class:
@Component({
selector: 'input.highlighter'
One clue that I found in the Angular doc 是:
Angular only allows directives to trigger on CSS selectors that do not cross element boundaries.
如何在 Angular 指令中定位组件内的特定元素。
我有一个带有选择器 "highlighter" 的组件。该组件具有使用 ng-content 的内容项目。
有一个带有选择器 "highlighter input" 的指令。
我相信该指令应该只应用于荧光笔组件内的任何输入,但它应用于应用程序中的所有输入 - 怎么了?
笨蛋: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
仍然不能工作。
最简单的解决方案是像这样向输入添加 class:
<input class="highlighter">
并在选择器中定位此 class:
@Component({
selector: 'input.highlighter'
One clue that I found in the Angular doc 是:
Angular only allows directives to trigger on CSS selectors that do not cross element boundaries.