首页 文章

Angular 4 Directive选择器仅用于定位组件内的元素

提问于
浏览
9

如何在Angular Directive中定位组件内的特定元素 .
我有一个带选择器"highlighter"的组件 . 该组件具有使用ng-content的内容项目 .
选择器"highlighter input"有一个指令 .
我相信这个指令应该仅应用于突出显示器组件内部的任何输入,但它应用于应用程序中的所有输入 - 这是错误的吗?

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';
    }
}

3 回答

  • 3

    Angular中的选择器不支持combinators

    - descendant selector (space)
    - child selector (>)
    - adjacent sibling selector (+)
    - general sibling selector (~)
    

    所以字符串中的最后一个不同的选择器获胜,在你的情况下是 input . 's why it'适用于所有输入 .

    另一件事是投影内容不被视为位于投影的组件内 . 因此,即使Angular支持组合子选择器,选择器 highlighter input 仍然不起作用 .

    最简单的解决方案是在输入中添加一个类,如下所示:

    <input class="highlighter">
    

    并在选择器中定位此类:

    @Component({
      selector: 'input.highlighter'
    
  • 0

    指令将应用于声明的模块中的所有选择器 .

  • 0

    One clue that I found in the Angular doc是这样的:

    Angular仅允许指令在不跨越元素边界的CSS选择器上触发 .

相关问题