ContentChildren angular 2 and reference to a HTMLElement

Viewed 503

I have a Component and I use it in this way:

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

I want in export class ImgListComponent to take a reference to the first image, I tried:

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

and in:

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

  }

but console displays undefined.

1 Answers

The first parameter of ContentChild and ContentChildren isn't a CSS selector but a component reference. You can create a fake component to reference all the images, like:

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

then you can implement your ContentChildren in this way:

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

remember to declare the new directive in your module.

Related