我有一个组件,我以这种方式使用它:
<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])
}
但控制台显示未定义。
答案 0 :(得分:1)
ContentChild
和ContentChildren
的第一个参数不是CSS选择器,而是组件引用。您可以创建一个伪造的组件来引用所有图像,例如:
@Directive({selector: 'img[foo]'}) exports class ImageDirective {}
然后您可以通过以下方式实现ContentChildren
:
@ContentChildren(ImageDirective) imgEls: QueryList<ImageDirective>;
请记住在模块中声明新指令。