Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Using Google Admob In Your NativeScript Angular Mobile App

TwitterFacebookRedditLinkedInHacker News

I recently received a request from one of my followers for a tutorial on using Google Admob in a NativeScript Angular application. Not too long ago I had demonstrated Google Admob in a vanilla NativeScript project, but I hadn’t yet given it a shot with Angular.

In case you’re unfamiliar with Admob, it is an excellent way to monetize your mobile applications with advertisements. You’ll earn revenue not only from people clicking your in-app advertisements, but also from the advertisements appearing on the screen.

We’re going to see how to use Admob in a NativeScript Android and iOS application that was built with Angular.

To get the most out of this tutorial, we’re going to start with a clean slate. Open your Command Prompt (Windows) or Terminal (Mac and Linux) and execute the following commands:

tns create AdmobProject --ng
cd AdmobProject
tns platform add android
tns platform add ios

The --ng flag in the above indicates that we are going to be building an Angular project with TypeScript. You’ll notice that I’m adding both the Android and iOS build platforms. If you’re not using a Mac, you won’t be able to build for iOS.

This project, like the vanilla project we had made previously, requires the nativescript-admob plugin that was created by Eddy Verbruggen. This plugin can be installed by executing the following:

tns plugin add nativescript-admob

Because we are using TypeScript in our project, we need to configure the type definitions that are included with the Admob plugin. While it isn’t a requirement, it definitely helps us out. Open the project’s references.d.ts file and add the following:

/// <reference path="./node_modules/tns-core-modules/tns-core-modules.d.ts" /> Needed for autocompletion and compilation.
/// <reference path="./node_modules/nativescript-admob/admob.d.ts" />

Now we’ll have features such as IDE autocomplete and a few others in our project.

NativeScript Angular Admob

The goal here is to create what is seen above. At this point in time, if you haven’t already, you should sign into the Google Admob dashboard and create two applications. The reason I say two is because you should create an iOS version and an Android version of the same application in the portal. This allows you to track statistics between the two platforms. Make sure you’ve created both a banner unit and an interstitial unit for each of the two applications.

Developing the TypeScript Logic for Our Admob Project

Open your project’s app/app.component.ts file and include the following TypeScript code:

import { Component } from "@angular/core";
import * as Admob from "nativescript-admob";

@Component({
    selector: "my-app",
    templateUrl: "app.component.html",
})
export class AppComponent {

    private androidBannerId: string = "ca-app-pub-XXXX/YYYY";
    private androidInterstitialId: string = "ca-app-pub-KKKK/LLLL";
    private iosBannerId: string = "ca-app-pub-RRRR/TTTT";
    private iosInterstitialId: string = "ca-app-pub-GGGG/HHHH";

    public constructor() { }

    public createBanner() {
        Admob.createBanner({
            testing: true,
            size: Admob.AD_SIZE.SMART_BANNER,
            iosBannerId: this.iosBannerId,
            androidBannerId: this.androidBannerId,
            iosTestDeviceIds: ["yourTestDeviceUDIDs"],
            margins: {
                bottom: 0
            }
        }).then(function() {
            console.log("admob createBanner done");
        }, function(error) {
            console.log("admob createBanner error: " + error);
        });
    }

    public hideBanner() {
        Admob.hideBanner().then(function() {
            console.log("admob hideBanner done");
        }, function(error) {
            console.log("admob hideBanner error: " + error);
        });
    }

    public createInterstitial() {
        Admob.createInterstitial({
            testing: true,
            iosInterstitialId: this.iosInterstitialId,
            androidInterstitialId: this.androidInterstitialId,
            iosTestDeviceIds: ["yourTestDeviceUDIDs"]
        }).then(function() {
            console.log("admob createInterstitial done");
        }, function(error) {
            console.log("admob createInterstitial error: " + error);
        });
    }

}

Since there is a lot of code in the above block, let’s break it down piece by piece.

import { Component } from "@angular/core";
import * as Admob from "nativescript-admob";

In the above we are importing the Angular dependency as well as the Admob dependency that we had installed via our Command Prompt or Terminal.

Inside the AppComponent class we have the following private variables:

private androidBannerId: string = "ca-app-pub-XXXX/YYYY";
private androidInterstitialId: string = "ca-app-pub-KKKK/LLLL";
private iosBannerId: string = "ca-app-pub-RRRR/TTTT";
private iosInterstitialId: string = "ca-app-pub-GGGG/HHHH";

These four variables should be set to the advertisement unit ids that you created in your Admob dashboard. I’ve just included placeholder values to give you an idea of what they look like. My values won’t work, but yours will.

Now we have three different methods for working with the advertisements, starting with the createBanner method:

public createBanner() {
    Admob.createBanner({
        testing: true,
        size: Admob.AD_SIZE.SMART_BANNER,
        iosBannerId: this.iosBannerId,
        androidBannerId: this.androidBannerId,
        iosTestDeviceIds: ["yourTestDeviceUDIDs"],
        margins: {
            bottom: 0
        }
    }).then(function() {
        console.log("admob createBanner done");
    }, function(error) {
        console.log("admob createBanner error: " + error);
    });
}

Using the imported NativeScript Admob plugin we can create a SMART_BANNER at the bottom of the screen using the set unit ids and any set test ids. You’ll also notice that the banner is set to be running in testing mode. This will prevent us from getting banned from Admob while we test with false hits.

Now in regards to the banner types. There are quite a few and they include the following:

  • SMART_BANNER
  • LARGE_BANNER
  • BANNER
  • MEDIUM_RECTANGLE
  • FULL_BANNER
  • LEADERBOARD
  • SKYSCRAPER
  • FLUID

I encourage you to do the research on what each banner type accomplishes.

There may be a scenario where we want to hide our banner. Maybe you have an in-app-purchase that removes advertisements and you want to hide it after they buy. That is where our hideBanner method comes into play:

public hideBanner() {
    Admob.hideBanner().then(function() {
        console.log("admob hideBanner done");
    }, function(error) {
        console.log("admob hideBanner error: " + error);
    });
}

The above doesn’t do anything beyond hiding our only banner advertisement.

Finally we have our interstitial advertisement. If used correctly, this type of advertisement could earn you the most revenue in your application. In the createInterstitial method we have the following:

public createInterstitial() {
    Admob.createInterstitial({
        testing: true,
        iosInterstitialId: this.iosInterstitialId,
        androidInterstitialId: this.androidInterstitialId,
        iosTestDeviceIds: ["yourTestDeviceUDIDs"]
    }).then(function() {
        console.log("admob createInterstitial done");
    }, function(error) {
        console.log("admob createInterstitial error: " + error);
    });
}

Again we’re using testing mode with the ids that we defined at the top of our TypeScript file. The difference here is that we’re using Admob.createInterstitial instead of trying to create a banner advertisement. The interstitial is like a popup where it takes up the full screen rather than a portion of the screen.

With the TypeScript out of the way, let’s create our simple yet powerful UI.

Creating the UI for Our Admob Project

The UI is going to be short and sweet. It is going to contain three buttons, that when pressed, will trigger each of the methods that we had created in our TypeScript code.

Open the project’s app/app.component.html file and include the following HTML markup:

<ActionBar title="Admob Example"></ActionBar>
<StackLayout>
    <Button text="Create Banner" (tap)="createBanner()" class="btn btn-primary"></Button>
    <Button text="Hide Banner" (tap)="hideBanner()" class="btn btn-primary"></Button>
    <Button text="Create Interstitial" (tap)="createInterstitial()" class="btn btn-primary"></Button>
</StackLayout>

As you can see in the above we have an action bar with three buttons. Each of the three buttons are styled using the included NativeScript theme. When tapped, the corresponding TypeScript method will be triggered to either show or hide a banner advertisement or show an interstitial advertisement.

Conclusion

You just saw how to use Google Admob in a NativeScript Angular project. This is an alternative to the vanilla tutorial that was previously written. Ad units are a great way to earn revenue in your mobile application without actually charging your users some kind of fee. Just remember to switch off the testing indicator when you go into production, otherwise you won’t make any money.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.