ContentChildren angular 2和对HTMLElement的引用

时间:2017-07-23 15:43:32

标签: angular-components

我有一个组件,我以这种方式使用它:

<ImgList>
    <img src="../assets/img/file1.jpg" width="30px" height="20px" />
    <img src="../assets/img/file2.jpg" width="30px" height="20px" />
</ImgList>

我想在export class ImgListComponent中引用第一张图片,我试过了:

@ContentChildren('img', {read: ElementRef}) imgEls: QueryList<ElementRef>;

并在:

ngAfterContentInit() {
    console.log(this.imgEls.toArray[0])

  }

但控制台显示未定义。

1 个答案:

答案 0 :(得分:1)

ContentChildContentChildren的第一个参数不是CSS选择器,而是组件引用。您可以创建一个伪造的组件来引用所有图像,例如:

@Directive({selector: 'img[foo]'}) exports class ImageDirective {}

然后您可以通过以下方式实现ContentChildren

@ContentChildren(ImageDirective) imgEls: QueryList<ImageDirective>;

请记住在模块中声明新指令。