nativescript Accessing native apis use native apis directly in javascript


Example

We want to add Toast to nativescript default app.

import {Component} from "@angular/core";
let application = require("application");

declare var android:any;

@Component({
    selector: "my-app",
    templateUrl: "app.component.html",
})
export class AppComponent {
    public counter: number = 16;

    public get message(): string {
        if (this.counter > 0) {
            return this.counter + " taps left";
        } else {
            return "Hoorraaay! \nYou are ready to start building!";
        }
    }

    public onTap() {
        this.counter--;
        this.showToast("You pressed the button","short");
    }



    public showToast(text:string ,StrDuration:string ):void{
      let duration:number;
      switch (StrDuration){
          case "short":
              duration = android.widget.Toast.LENGTH_SHORT;
              break;
          case "long":
              duration = android.widget.Toast.LENGTH_LONG;
              break;
      }    
        android.widget.Toast.makeText(application.android.context,text, android.widget.Toast.LENGTH_SHORT).show();
   }
}

for creating toast we should call Toast.makeText and it's in the android.widget.Toast package. Toast.makeText accepts context as first argument and we can get the context in nativescript in this way:application.android.context