ionic 2 app tutorial, a simple YouTube player

Welcome again, today we will build a YouTube player in ionic framework 2 using the YouTube api for search videos and the YouTube iframe api for play videos, so let’s begin.

Ionic framework is a tool for making mobile apps using angular 1 and 2, today we going to be using the version 2 of the framework. for this tutorial you will need to know some typescript,css and html.

Ok so first you need to install ionic on your computer with the  command

npm install -g cordova ionic

Assuming that you already have installed npm and nodejs.

Then create a new project

ionic start ionic-youtube-ng2 blank

This setup for us the ionic blank project, if you want to tested right now you need to get in the directory and type ionic serve and that’s it, the project is running now and we can see it on the browser.

If everything is ok the app is now running on the browser and we can start coding the app, there is not need to reload because the app will refresh automatically.

Ok we will code two services for our app, the first one we call it player.service.ts and we will put it on /src/services folder, this one is for using the iframe api so in order to use this api we need to load it when the app start so in the app.component.ts we need to add these lines on the constructor.

      var tag = document.createElement('script');
      tag.src = "";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

And in the app.module.ts import the required providers.

import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { BrowserModule } from '@angular/platform-browser';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { HttpModule } from '@angular/http';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

  declarations: [
  imports: [
  bootstrap: [IonicApp],
  entryComponents: [
  providers: [
        {provide: ErrorHandler, useClass: IonicErrorHandler},
        {provide: Window, useValue: window}
export class AppModule {}

And in the player.service.ts

import { Injectable } from '@angular/core';

export class PlayerService {
  youtube: any = {
    ready: false,
    player: null,
    playerId: null,
    videoId: null,
    videoTitle: null,
    playerHeight: '360',
    playerWidth: '640'

  constructor() {

  bindPlayer(elementId): void { = elementId;

  createPlayer(): void {
    return new window['YT'].Player(, {
      playerVars: {
        rel: 0,
        showinfo: 0

  loadPlayer(): void {
    if ( && {
      if ( {;
      } = this.createPlayer();

  setupPlayer() {
    //we need to check if the api is loaded
    window['onYouTubeIframeAPIReady'] = () => {
      if (window['YT']) { = true;
    if (window['YT'] && window['YT'].Player) { = true;

  launchPlayer(id): void {; = id;

Ok we have the player service done, to use it we need a video id, so next we code the youtube.service.ts, this one is for search for videos, it can to a lot more but in our app we only going to search and play videos.

import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';


export class YoutubeService {
     googleToken = "your token goes here";
     maxResults = 10;
     url = ',snippet&q=';
     constructor(public http: Http) {}
     public getVideos(query:any){
        return this.http.get(this.url+query+'&type=video&order=viewCount&maxResults='+this.maxResults+'&key='+this.googleToken)
         .map(res => res.json());


This service need a google token, you can get one in the google console.

So let’s code view. inside src/pages/ there are our views and in this case we have a home.html, home.scss and a home.ts. home.ts is our main component, in the end this is angular 2 so in the home.ts we are going to call the services that we created.

import { Component } from '@angular/core';

import { NavController,LoadingController } from 'ionic-angular';

import { YoutubeService } from '../../services/youtube.service'
import {PlayerService} from '../../services/player.service';

  selector: 'page-home',
  templateUrl: 'home.html',
export class HomePage {
  vPlayer = true;
  videos = {};
  search = {

  constructor(public navCtrl: NavController,public player: PlayerService,public youtubeService: YoutubeService,public loadingCtrl:LoadingController) {
    let loading = this.loadingCtrl.create({

      videos => {
  baseUrl:string = '';

    this.vPlayer = true; 



And in the html


<ion-content padding>
<div id="player" class="embed-responsive embed-responsive-16by9">
<div id="placeholder" style="width: 100%" class="embed-responsive-item"></div>
<div class="embed-responsive-item" style="width: 100% ; z-index: 90;position: fixed; background-color: black; background: url('images/cover.png'); background-size:cover; " *ngIf="!onPlaying"></div>
<div id="search-form">
<form (ngSubmit)="findVideos($event)">
                <ion-label floating>Search Videos</ion-label>
                <ion-input type="text" [(ngModel)]="search.params" name="search"></ion-input>
                <button type="submit" ion-button icon-only clear item-right>
          <ion-icon name="search"></ion-icon>

<div id="results">
<div class="card-background-page">
            <ion-card *ngFor="let video of videos.items">
                <img src="{{video.snippet.thumbnails.high.url}}" />
<div class="card-title">
<div class="card-subtitle">
<button class="card-btn" (click)="playVideo(">
  <ion-icon name="play"></ion-icon>

As we can see there is two parts in the view, one is the player, and the other are the search forms and the results. with all this we have now a simple youtube client that can run on android or ios.
and the styles…

page-home {}

.card-background-page {
    ion-card {
        position: relative;
        text-align: center;
    .card-title {
        position: absolute;
        top: 36%;
        font-size: 2.0em;
        width: 100%;
        font-weight: bold;
        color: #fff;
        text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
    .card-subtitle {
        font-size: 1.0em;
        position: absolute;
        top: 82%;
        width: 100%;
        color: #fff;
        text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
    .card-btn {
        font-size: 6.0em;
        padding-top: 1%;
        padding-bottom: 1%;
        padding-left: 3%;
        padding-right: 3%;
        position: absolute;
        top: 50%;
        width: 20%;
        left: 40%;
        color: white;
        border-radius: 25%;
        background-color: #333;
    .card-btn:hover {
        background-color: red;

For compiling in to an android app we need the android sdk installed in our system, if you have de android sdk to compile the app we type in the terminal this.

ionic platform add android 


ionic build android 

And the .apk is generate in platforms/android/build/outputs/apk/

so that’s all. see ya next time.

the code was updated to work with ionic 3.

Source Code


5 thoughts on “ionic 2 app tutorial, a simple YouTube player

    1. hello, i just update the package.json with the latest ionic apps but i was unable to replicate the error, even on diferents machines with diferents os. what is your setup?
      (updated) the issue is happening with angular 4. so i just update the project to work with ionic 3, and angular 4.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s