@ViewChild undefined

Before you judge, I’ll let you know that I’ve checked every single search result that popped out to no avail.

I’m trying to get an HTML5 Audio Element to autoplay upon page enter.
page-page.html:

<audio #audio id="audio" controls controlsList="nodownload">
   <source [src]="audioUrl" type="audio/mpeg">
   Sum Ting Wong.
</audio>

page-component.ts:

import { Component, ViewChild, ElementRef } from '@angular/core';

@IonicPage()
@Component({
  selector: 'page-page-page',
  templateUrl: 'page-page.html',
})
export class PagePage {
   @ViewChild('audio') elemElem;
   ...
   ngAfterViewInit () {
      console.log(this.elemElem); // Is always undefined.
   }
}

I don’t know why it’s always undefined. I’ve tried things like using the @ViewChild() within ngAfterViewInit() but of course, it’s not allowed.

Is that the entirety of the template? Is there a chance that some conditional directive like ngIf is somehow getting involved? @ViewChild doesn’t like it when its target is not always in the DOM.

3 Likes

Darn it. You’re right! That’s all I actually needed.

I changed its parent <div> from this:

<div *ngIf="isReady">

… to this:

<div [hidden]="!isReady">

Thanks!

2 Likes

This was my solution…