Angular 2 @ViewChild returns undefined

Try using a ref in your template instead:

<div id='gallery-container' #galleryContainer class="gallery-image-container">
    <div class="gallery-padding"></div>
    <img class="gallery-image" src="https://stackoverflow.com/questions/39256703/{{ coverPhotoVm }}" />
    <img class="gallery-image" src="{{ imagepath }}" *ngFor="let imagepath of imagesVm" />
</div>

And use the ref name as the argument:

@ViewChild('galleryContainer') galleryContainer: ElementRef;

EDIT

Forgot to mention that any view child thus declared is only available after the view is initialized. The first time this happens is in ngAfterViewInit (import and implement the AfterViewInit interface).

The ref name must not contain dashes or this will not work

Leave a Comment