[SOLVED] ViewChild not resolving custom component


I’m trying to resolve a custom component in my page, but no matter what I do, it is always undefined.

I’ve followed the documentation here: http://learnangular2.com/viewChild/ and it seems like I’m doing everything the same.


import { Component, ViewChild } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { AudioPlayer } from '../../components/audio-player/audio-player';

  template: '<audio-player #audio1></audio-player>',
  directives: [AudioPlayer]
export class AsanaPage {
  @ViewChild(AudioPlayer) audio: AudioPlayer;
  // @ViewChild('audio1') audio: AudioPlayer; // same problem 

  constructor(private nav: NavController, private navParams: NavParams) {
    console.log('AudioPlayer: ');
    console.log(this.audio); // displays 'undefined'


import { Component } from '@angular/core';
import { IONIC_DIRECTIVES } from 'ionic-angular';

  selector: 'audio-player',
  template: '<button (click)="audioToggled($event)">',
  directives: [AudioPlayer]
export class AudioPlayer {
  private player: any;

  constructor() {
    console.log('Creating AudioPlayer');

Output on console:

Creating AudioPlayer

Note the order of the output, that the AudioPlayer constructor is being created after the including page’s constructor is run. I don’t know if that’s the problem, but it is interesting.


You should not be doing anything regarding @ViewChild in constructors. Try using ngAfterViewInit instead.


Awesome, that solves it thanks!