angular – 如何获取Component中投影的所有元素的引用?

前端之家收集整理的这篇文章主要介绍了angular – 如何获取Component中投影的所有元素的引用?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我想获得对Component中投影的所有元素的引用,我该怎么办?

假设我有AppComponent将一些链接和图像投影到TestComponent中:

@Component({
  selector: 'test',template: '<ng-content></ng-content>'
})
class TestComponent {}

@Component({
  selector: 'app',template: `
    <test>
      <img src="http://example.org/1.jpg">
      <a href="http://example.org">Some Link</a>
    </test>
  `,directives: [ TestComponent ]
})
export class AppComponent {}

现在,我如何在TestComponent中获得对这些链接和图像(以及可能的其他元素类型)的引用?

阅读this post建议如下:

Solution: ContentChildren + directive with li selector

One great solution is to take advantage of the selector in the
@Directive decorator. You simply define a directive that selects for
<li> elements,then use a @ContentChildren query to filter all <li>
elements down to only those that are content children of the
component.

但是这只有在我想获得单个元素类型时才有效,但是如果我想获得多个类型,这意味着我必须为我想要的每种类型创建一个指令(如果我想要所有类型,那该怎么办?)……这不是一种实用的方法.

还有另外一种方法吗?或直接DOM操作是这种情况下唯一的解决方案?

解决方法

您可以尝试在指令上使用多个选择器,如下所示:

@Directive({ selector: 'a,img' })

Angular仅允许指令在不跨越元素边界的CSS选择器上触发.因此,选择器可以声明为以下之一:

> element-name:按元素名称选择.> .class:按类名选择.> [attribute]:按属性名称选择.> [attribute = value]:按属性名称和值选择.>:not(sub_selector):仅在元素与sub_selector不匹配时选择.> selector1,selector2:如果selector1或selector2匹配则选择.

猜你在找的Angularjs相关文章