加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:50:43 所属栏目:安全 来源:网络整理
导读:如果我想获得对Component中投影的所有元素的引用,我该怎么办? 假设我有AppComponent将一些链接和图像投影到TestComponent中: @Component({ selector: 'test',template: 'ng-content/ng-content'})class TestComponent {}@Component({ selector: 'app',temp
如果我想获得对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匹配则选择.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读