Improve this

Angular 2+

Before reading this section, we suggest you reading Getting Started and Fundamentals to grasp the basics of Onsen UI. Don’t worry, it won’t take more than 5 minutes.

In this chapter, we will show you how to use ngx-onsenui, Onsen UI’s binding library for Angular.

Setup

Prerequisites

This document assumes you are somewhat familiar with Angular framework, and have an existing Angular application. If not, we suggest you to go through the official Angular guide and setup an initial project.

Install onsenui and ngx-onsenui

Use npm to install Onsen UI Core (onsenui) and the binding library for Angular (ngx-onsenui).

npm install onsenui ngx-onsenui --save
Import OnsenModule

Then, import OnsenModule into the root module (typically called AppModule) of your Angular app.

import { OnsenModule } from 'ngx-onsenui';
imports: [
   BrowserModule,
   OnsenModule,
],

This step will load all components and features of ngx-onsenui and Onsen UI Core (onsenui) into your app.

Load CUSTOM_ELEMENTS_SCHEMA

Add schemas property into the root module and put CUSTOM_ELEMENTS_SCHEMA into it. This is important since Onsen UI components are Web Components (Custom Elements).

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
  schemas: [
      CUSTOM_ELEMENTS_SCHEMA,
  ],

This step suppresses warnings caused by ons-* tags in templates.

Load CSS files

Finally, load onsenui.css and onsen-css-components.css in node_modules/onsenui/css/. Make sure to do in this order!

Using Angular CLI

Append the following two lines in angular.json (.angular-cli.json for Angular 2-5). Check out the official Angular CLI guide for more details.

"styles": [
  "node_modules/onsenui/css/onsenui.css",
  "node_modules/onsenui/css/onsen-css-components.css",
  "src/styles.css"
],

Configure Manually

Modify the following two lines appropriately and append them into the global stylesheet file in your project.

@import 'node_modules/onsenui/css/onsenui.css';
@import 'node_modules/onsenui/css/onsen-css-components.css';
Ready to go!

ngx-onsenui has been set up. Have fun with Onsen UI components for Angular!

ngx-onsenui Essentials

Using components

ngx-onsenui provides various components: (see all components in list). Each components start with ons-* tag.

For example, let’s put a button.

template: `
  <ons-button>Click Me</ons-button>
`

If you want to set an action triggered when the button is clicked, you can use Angular event binding.

template: `
  <ons-button (click)="doSomething()">Click Me</ons-button>
`

If you want to know what events you can use in each component, please refer to each reference page of them.

Two-way binding

Some components (i.e. ons-input) support two-way binding. They allow [(value)]="val" syntax to synchronize the value of val with the value of ons-input.

template: `
  <ons-input type="text" [(value)]="val"></ons-input>: {{val}}
`

Some components require (input)="val = $event.target.value" in addition to [(value)]="val" syntax. For example, ons-range component won’t update the value when it’s dragged.

template: `
  <ons-range [(value)]="val" (input)="val = $event.target.value"></ons-range>
`
Using ons-page

ons-page is a special component which covers the whole screen and becomes the container for the toolbar.

ons-page must be created by writing the following code:

<ons-page>
  <div class="background"></div><!-- Background of the page -->
  <div class="content">
    <!-- Content of the page -->
  </div>
</ons-page>

background corresponds to the background of the page, and content corresponds to the content of the page. Keep in mind that page contents cannot be placed right under the ons-page.

Similarily, ons-toolbar can be used to show a toolbar at the top of the page. In this case, ons-toolbar has to be the direct first child of ons-page.

<ons-page>
  <ons-toolbar>
    <div class="center"><!-- Toolbar title --></div>
  </ons-toolbar>
  <div class="background"></div>
  <div class="content">
    <!-- Content of the page -->
  </div>
</ons-page>
Managing pages with navigator, splitter and tabbar

ngx-onsenui provides three special components to mangae pages: ons-navigator, ons-splitter and ons-tabbar. They allow native-like page transitions.

Page managers will automatically create, destroy and animate multiple ons-pages. Let’s see in code with ons-navigator.

Defining a page

To use page managers, each pages need to be defined as Angular components. It can be achieved by setting ons-page[some-id] for the selector and describing the page content inside template.

@Component({
  selector: 'ons-page[first]',
  template: `
    <ons-toolbar>
      <div class="center">First</div>
    </ons-toolbar>
    <div class="background"></div>
    <div class="content">
      First page
    </div>
  `
})
export class FirstPageComponent {
}

A unique page ID should be specified (first in the example above). Otherwise, the original definition of the ons-page directive will be broken and it leads to unexpected behavior.

Then, add the page component into entryComponents property of the root module (Typical name: AppModule).

  entryComponents: [
    FirstPageComponent
  ],

This step is required so that ons-navigator can dynamically create and destroy FirstPageComponent. If not, No component factory found for FirstPageComponent error will be shown.

Set default page of ons-navigator

Now ons-navigator component is available. Use [page] attribute to specify the default page.

@Component({
  selector: 'app-root',
  template: `
    <ons-navigator [page]="initialPage"></ons-navigator>
  `
})
export class AppComponent {
  initialPage = FirstPageComponent;
}

With the code above, it will show the page content in FirstPageComponent component.

And in this example, we defined initialPage and assigned the value to it. It is because Angular does not allow using a variable (FirstPageComponent) outside the class.

Pushing a page

ons-navigator manages pages in the form of a stack. Adding a page to the front screen is called “push”, and removing a foremost page is called “pop”.

Let’s try pushing another page content when a button is pressed.

First, define another page with the name SecondPageComponent and add it into entryComponents property.

@Component({
  selector: 'ons-page[second]',
  template: `
    <ons-toolbar>
      <div class="center">Second</div>
    </ons-toolbar>
    <div class="background"></div>
    <div class="content">
      Second page
    </div>
  `
})
export class SecondPageComponent {
}
  entryComponents: [
    FirstPageComponent,
    SecondPageComponent
  ],

Then, add a button and a short code to push FirstPageComponent page.

import { OnsNavigator } from 'ngx-onsenui';

@Component({
  selector: 'ons-page[first]',
  template: `
    <ons-toolbar>
      <div class="center">First</div>
    </ons-toolbar>
    <div class="background"></div>
    <div class="content">
      First page<br>
      <ons-button (click)="push()">Push</ons-button>
    </div>
  `
})
export class FirstPageComponent {
  // Get a way to access `ons-navigator` by Dependency Injection (DI)
  constructor(private navigator: OnsNavigator) {
  }

  push() {
    // Push SecontPageComponent to `ons-navigator
    this.navigator.element.pushPage(SecondPageComponent);
  }
}

Voila. The page defined by SecondPageComponent will slide from the right when the button is pressed.

To summarize, pushing pages to ons-navivator requires the following two steps:

  1. Give a way (= the directive instance) to access ons-navigator by Dependency Injection (DI)
  2. Push SecondPageComponent to ons-navigator with pushPage

Please note that the method to call is this.navigator.element.pushPage, and not this.navigator.pushPage.

Similarly, if you want to pop pages, execute this.navigator.element.popPage when SecondPageComponent is displayed.

Passing parameters to the new page

You can pass parameters to a destination page when a pushing / popping page.

To pass a parameter, use data option when calling pushPage:

this.navigator.element.pushPage(SecondPageComponent, {data: {foo: 1234}});

Passed parameters can be received in the destination page using Dependency Injection (DI).

import { Params } from 'ngx-onsenui';
constructor(private params: Params) {
  console.log(JSON.stringify(params.data)); // => {"foo": 1234}
}

pushPage has several options as well as data option such as animationoption (for more details, please refer to ons-navigator). You can retrieve all the options with Params as well as data option.

More examples

Each components are equipped with working examples. Please refer to examples directory in the repository.

For instance, carousel.ts contains information about what code you would write when using ons-carousel compoennt.

Architecture

This section may contain advanced information.

Wrapping Web Components with Angular directives

ngx-onsenui provides a feature to set default page with [page], two-way binding and other features, which cannot be realized by features of Web Components itself, by wrapping elements defined in Web Components layer with Angular directives.

For example, ons-navigator element is wrapped with OnsNavigator directive and ons-switch element is wrapped with OnsSwitch directive.

However not all the components have corresponding directives. For example, ons-button element is not wrapped with any directives since there is no need to wrap the element.

About the list of all the directives provided by ngx-onsenui, please refer to the definition of OnsenModule (GitHub).

How to directly call methods in Web Components layer

In Web Components, methods are directly defined in DOM elements. To call the methods, you can access elements in some way such as querySelector().

In Angular, you can also access DOM elements with template reference variables (Example: #var). For more details, please refer to the official Angular guide.

About angular2-onsenui

angular2-onsenui which is previously provided has been obsoleted since Angular 4 was announced. If you are still using angular2-onsenui, we recommend that you update it to ngx-onsenui.