Create an Animated Authentication Screen With NativeScript

This post will show you how to create an animated authentication screen, using NativesScript and Angular 2.

In the end, we want be able to able to swap the two screens (login and registration) by tapping on a control, like demonstrated on this video:

The whole source code is also available on GitHub at this address.

Let’s get started!

Setup

First step, create the application with the –ng flag:

tns create tns-animated-auth --ng 1 tns create tns - animated - auth -- ng

Next, let’s go and install the nativescript-ng2-fonticon package as we’re going to use it later on.

When this is done, we’ll create our first Component, the SessionComponent . To keep things organised, We’ll put it into a new session directory, and let it empty for now:

// app/session/session.component.ts import { Component } from '@angular/core'; @Component({ selector: 'session', templateUrl: 'session/session.component.html', styleUrls: ['session/session.component.css'] }) export class SessionComponent { } 1 2 3 4 5 6 7 8 9 10 11 // app/session/session.component.ts import { Component } from '@angular/core' ; @ Component ( { selector : 'session' , templateUrl : 'session/session.component.html' , styleUrls : [ 'session/session.component.css' ] } ) export class SessionComponent { }

Next, pack the SessionComponent into a new Module:

// app/session/session.module.ts import { NgModule } from '@angular/core'; import { SessionComponent } from './session.component'; @NgModule({ declarations: [SessionComponent], exports: [SessionComponent], imports: [], providers: [] }) export class SessionModule {} 1 2 3 4 5 6 7 8 9 10 11 12 // app/session/session.module.ts import { NgModule } from '@angular/core' ; import { SessionComponent } from './session.component' ; @ NgModule ( { declarations : [ SessionComponent ] , exports : [ SessionComponent ] , imports : [ ] , providers : [ ] } ) export class SessionModule { }

We’ll now configure the Router, in order to get started on a healthy base. This is a better idea than polluting the AppComponent with unrelated stuff just because we want to see something happening.

Create a file exporting our only route:

// app/app.routes.ts import { SessionComponent } from './session/session.component'; export const routes = [ { path: '', component: SessionComponent } ]; 1 2 3 4 5 6 7 // app/app.routes.ts import { SessionComponent } from './session/session.component' ; export const routes = [ { path : '' , component : SessionComponent } ] ;

Next, import the NativeScrpiptRouterModule , and import the routes constant we’ve just created. We’ll also import the SessionModule :

// app/app.module.ts import { NgModule } from '@angular/core'; import { NativeScriptModule } from 'nativescript-angular/platform'; import { NativeScriptRouterModule } from 'nativescript-angular/router'; import { TNSFontIconModule } from 'nativescript-ng2-fonticon'; import { SessionModule } from './session/session.module'; import { AppComponent } from './app.component'; import { routes } from './app.routes'; @NgModule({ declarations: [AppComponent], bootstrap: [AppComponent], imports: [ SessionModule, NativeScriptModule, NativeScriptRouterModule, NativeScriptRouterModule.forRoot(routes), TNSFontIconModule.forRoot({ 'fa': 'font-awesome.css' }) ] }) export class AppModule { } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // app/app.module.ts import { NgModule } from '@angular/core' ; import { NativeScriptModule } from 'nativescript-angular/platform' ; import { NativeScriptRouterModule } from 'nativescript-angular/router' ; import { TNSFontIconModule } from 'nativescript-ng2-fonticon' ; import { SessionModule } from './session/session.module' ; import { AppComponent } from './app.component' ; import { routes } from './app.routes' ; @ NgModule ( { declarations : [ AppComponent ] , bootstrap : [ AppComponent ] , imports : [ SessionModule , NativeScriptModule , NativeScriptRouterModule , NativeScriptRouterModule . forRoot ( routes ) , TNSFontIconModule . forRoot ( { 'fa' : 'font-awesome.css' } ) ] } ) export class AppModule { }

Now we can edit the AppComponent to display the in its template:

// app/app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: `<page-router-outlet></page-router-outlet>` }) export class AppComponent { } 1 2 3 4 5 6 7 8 9 10 // app/app.component.ts import { Component } from '@angular/core' ; @ Component ( { selector : 'my-app' , template : ` < page - router - outlet > < / page - router - outlet > ` } ) export class AppComponent { }

We’re now ready to get into the meat of our application.

Structure the SessionComponent

Edit the session.component.html file with the following initial content:

<GridLayout class="container" rows="*, auto"> <GridLayout row="0"> <StackLayout #loginWrapper> </StackLayout> <StackLayout #registerWrapper> </StackLayout> </GridLayout> <StackLayout row="1"> </StackLayout> </GridLayout> 1 2 3 4 5 6 7 8 9 10 < GridLayout class = "container" rows = "*, auto" > < GridLayout row = "0" > < StackLayout #loginWrapper> < / StackLayout > < StackLayout #registerWrapper> < / StackLayout > < / GridLayout > < StackLayout row = "1" > < / StackLayout > < / GridLayout >

To structure the screen, we use a GridLayout. We define two rows: one containing the login/registration forms, and one for the footer, enabling the switch to the new current screen (login or registration).

The login and registration forms will be hosted in their own components, and we’re going to wrap them into StackLayouts in order to easily control their apparition of the screen.

We also want to have both of them inside a GridLayout. This way, they will be displayed on top of each other, which is what we want (we’ll take care of the horizontal axis separation programmatically).

Let’s now create the LoginComponent .

Create the LoginComponent

First, create the empty Component in a new login directory, within the session one. We’ll inject the TNSFontIconService as we’re going to use it in the template:

// app/session/login/login.component.ts import { Component } from '@angular/core'; import { TNSFontIconService } from 'nativescript-ng2-fonticon'; @Component({ selector: 'login', templateUrl: 'session/login/login.component.html', styleUrls: ['session/common.css'] }) export class LoginComponent { constructor(private fonticon: TNSFontIconService) {} } 1 2 3 4 5 6 7 8 9 10 11 12 13 // app/session/login/login.component.ts import { Component } from '@angular/core' ; import { TNSFontIconService } from 'nativescript-ng2-fonticon' ; @ Component ( { selector : 'login' , templateUrl : 'session/login/login.component.html' , styleUrls : [ 'session/common.css' ] } ) export class LoginComponent { constructor ( private fonticon : TNSFontIconService ) { } }

We will use a common.css stylesheet file instead of a login specific one, since we’ll reuse most of the styling for the register later on.

Next, create the login.component.html template:

<!-- app/session/login/login.component.html --> <StackLayout> <StackLayout class="form-container"> <Label class="fa session-icon" [text]="'fa-sign-in' | fonticon"></Label> <TextField hint="Login"></TextField> <TextField hint="Password"></TextField> <Button text="Login"></Button> <StackLayout class="horizontal-separator"></StackLayout> <Label class="caption" text="Or Login with:"></Label> <StackLayout class="social-buttons-container" orientation="horizontal"> <Label class="fa social-icon" [text]="'fa-facebook-square' | fonticon"></Label> <Label class="fa social-icon" [text]="'fa-twitter-square' | fonticon"></Label> </StackLayout> </StackLayout> </StackLayout> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <!-- app/session/login/login.component.html --> <StackLayout> <StackLayout class = "form-container" > <Label class = "fa session-icon" [ text ] = "'fa-sign-in' | fonticon" > </Label> <TextField hint = "Login" > </TextField> <TextField hint = "Password" > </TextField> <Button text = "Login" > </Button> <StackLayout class = "horizontal-separator" > </StackLayout> <Label class = "caption" text = "Or Login with:" > </Label> <StackLayout class = "social-buttons-container" orientation = "horizontal" > <Label class = "fa social-icon" [ text ] = "'fa-facebook-square' | fonticon" > </Label> <Label class = "fa social-icon" [ text ] = "'fa-twitter-square' | fonticon" > </Label> </StackLayout> </StackLayout> </StackLayout>

And the styling:

/* app/session/common.css */ StackLayout.form-container { width: 75%; border-bottom-width: 1; } StackLayout, Button { border-color: rgba(255, 255, 255, 0.5); } TextField { font-size: 15; background-color: rgba(255, 255, 255, 0.18); padding-left: 15; margin-bottom: 10; height: 44; } Button { background-color: rgba(255, 255, 255, 0); border-width: 2; margin-bottom: 20; width: 60%; } Button, TextField { border-radius: 8; padding: 10; margin-top: 5; font-weight: bold; } Label.session-icon { margin-top: 50; margin-bottom: 20; text-align: center; font-size: 64; } Label.caption { text-align: center; margin-top: 10px; font-size: 15; } Button, TextField, Label.fa, Label.caption { color: #FFFFFF; } StackLayout.social-buttons-container { font-size: 32; horizontal-align: center; } Label.social-icon { padding: 10px; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 /* app/session/common.css */ StackLayout.form-container { width : 75% ; border-bottom-width : 1 ; } StackLayout, Button { border-color : rgba ( 255, 255, 255, 0.5 ) ; } TextField { font-size : 15 ; background-color : rgba ( 255, 255, 255, 0.18 ) ; padding-left : 15 ; margin-bottom : 10 ; height : 44 ; } Button { background-color : rgba ( 255, 255, 255, 0 ) ; border-width : 2 ; margin-bottom : 20 ; width : 60% ; } Button, TextField { border-radius : 8 ; padding : 10 ; margin-top : 5 ; font-weight : bold ; } Label.session-icon { margin-top : 50 ; margin-bottom : 20 ; text-align : center ; font-size : 64 ; } Label.caption { text-align : center ; margin-top : 10px ; font-size : 15 ; } Button, TextField, Label.fa, Label.caption { color : #FFFFFF ; } StackLayout.social-buttons-container { font-size : 32 ; horizontal-align : center ; } Label.social-icon { padding : 10px ; }

Notice the use of border-bottom-width for the form-container. The possibility to use per-side border definition in CSS is one of the awesome features coming out of the new NativeScript 2.4 release.

Let’s add the LoginComponent to the SessionModule declarations list:

import { NgModule } from '@angular/core'; import { SessionComponent } from './session.component'; import { LoginComponent } from './login/login.component'; import { TNSFontIconModule } from 'nativescript-ng2-fonticon'; @NgModule({ declarations: [ SessionComponent, LoginComponent ], exports: [SessionComponent], imports: [ TNSFontIconModule.forRoot({ 'fa': 'font-awesome.css' })], providers: [] }) export class SessionModule {} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import { NgModule } from '@angular/core' ; import { SessionComponent } from './session.component' ; import { LoginComponent } from './login/login.component' ; import { TNSFontIconModule } from 'nativescript-ng2-fonticon' ; @ NgModule ( { declarations : [ SessionComponent , LoginComponent ] , exports : [ SessionComponent ] , imports : [ TNSFontIconModule . forRoot ( { 'fa' : 'font-awesome.css' } ) ] , providers : [ ] } ) export class SessionModule { }

And add the selector to inside the corresponding wrapper, that we created in the session.component.html :

<!-- app/session/session.component.html --> [...] <StackLayout #loginWrapper> <login></login> </StackLayout> [...] 1 2 3 4 5 6 7 <!-- app/session/session.component.html --> [...] <StackLayout # loginWrapper > <login> </login> </StackLayout> [ . . . ]

Now, you can start the application, which should look like this:



It would be nice if we could also have the hint colors of the TextFields in white. Let’s create a directive for this. We’ll do it based on the following idea and separate the platform implementations into two distinct files.

Create the HintColorDirective

Create a new directory: directives/hint-color . Then, start by creating the HintColorBaseDirective , as suggested on the mentioned GitHub issue:

// app/directives/hint-color/hint-color.base.directive.ts import { ElementRef, Input } from '@angular/core'; import { TextField } from 'ui/text-field'; import { Color } from 'color'; export abstract class HintColorBaseDirective { constructor(private el: ElementRef) {} @Input() set hintColor(value: string) { const textField = <TextField>this.el.nativeElement; this.setColor(textField, new Color(value)); } protected abstract setColor(view: TextField, color: Color); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // app/directives/hint-color/hint-color.base.directive.ts import { ElementRef , Input } from '@angular/core' ; import { TextField } from 'ui/text-field' ; import { Color } from 'color' ; export abstract class HintColorBaseDirective { constructor ( private el : ElementRef ) { } @ Input ( ) set hintColor ( value : string ) { const textField = < TextField > this . el . nativeElement ; this . setColor ( textField , new Color ( value ) ) ; } protected abstract setColor ( view : TextField , color : Color ) ; }

This is the abstract class that needs to be inherited from the ones representing each platform (android, and ios). The only thing that it does, is calling the abstract method setColor() , passing the ElementRef (here, a TextField) and a new Color object created from the color code in input.

We can now define a child directive per platform.

Start with Android:

//app/directives/hint-color/hint-color.directive.android.ts import { Directive, ElementRef } from '@angular/core'; import { TextField } from 'ui/text-field'; import { Color } from 'color'; import { HintColorBaseDirective } from './hint-color.base.directive'; @Directive({ selector: '[hintColor]' }) export class HintColorDirective extends HintColorBaseDirective { constructor(el: ElementRef) { super(el); } protected setColor(view: TextField, color: Color) { view.android.setHintTextColor(color.android); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 //app/directives/hint-color/hint-color.directive.android.ts import { Directive , ElementRef } from '@angular/core' ; import { TextField } from 'ui/text-field' ; import { Color } from 'color' ; import { HintColorBaseDirective } from './hint-color.base.directive' ; @ Directive ( { selector : '[hintColor]' } ) export class HintColorDirective extends HintColorBaseDirective { constructor ( el : ElementRef ) { super ( el ) ; } protected setColor ( view : TextField , color : Color ) { view . android . setHintTextColor ( color . android ) ; } }

And then, iOS:

// app/directives/hint-color/hint-color.directive.ios.ts import { Directive, ElementRef } from '@angular/core'; import { TextField } from 'ui/text-field'; import { Color } from 'color'; import { HintColorBaseDirective } from './hint-color.base.directive'; declare const NSAttributedString: any; declare const NSDictionary: any; declare const NSForegroundColorAttributeName: any; @Directive({ selector: '[hintColor]' }) export class HintColorDirective extends HintColorBaseDirective { constructor(el: ElementRef) { super(el); } protected setColor(view: TextField, color: Color) { let dictionary = new NSDictionary( [color.ios], [NSForegroundColorAttributeName] ); view.ios.attributedPlaceholder = NSAttributedString.alloc().initWithStringAttributes(view.hint, dictionary); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // app/directives/hint-color/hint-color.directive.ios.ts import { Directive , ElementRef } from '@angular/core' ; import { TextField } from 'ui/text-field' ; import { Color } from 'color' ; import { HintColorBaseDirective } from './hint-color.base.directive' ; declare const NSAttributedString : any ; declare const NSDictionary : any ; declare const NSForegroundColorAttributeName : any ; @ Directive ( { selector : '[hintColor]' } ) export class HintColorDirective extends HintColorBaseDirective { constructor ( el : ElementRef ) { super ( el ) ; } protected setColor ( view : TextField , color : Color ) { let dictionary = new NSDictionary ( [ color . ios ] , [ NSForegroundColorAttributeName ] ) ; view . ios . attributedPlaceholder = NSAttributedString . alloc ( ) . initWithStringAttributes ( view . hint , dictionary ) ; } }

I think that it’s generally a good idea to make such a separation when dealing with platform specific code. This enables us to adapt only the specific file, when a change has to occur for one of the platforms.

Before being able to use the directive, we need to declare it into our SessionModule :

// app/session/session.module.ts import { NgModule } from '@angular/core'; import { SessionComponent } from './session.component'; import { LoginComponent } from './login/login.component'; import { TNSFontIconModule } from 'nativescript-ng2-fonticon'; const { HintColorDirective } = require('../directives/hint-color/hint-color.directive'); @NgModule({ declarations: [ SessionComponent, LoginComponent, HintColorDirective ], exports: [SessionComponent], imports: [ TNSFontIconModule.forRoot({ 'fa': 'font-awesome.css' })], providers: [] }) export class SessionModule {} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 // app/session/session.module.ts import { NgModule } from '@angular/core' ; import { SessionComponent } from './session.component' ; import { LoginComponent } from './login/login.component' ; import { TNSFontIconModule } from 'nativescript-ng2-fonticon' ; const { HintColorDirective } = require ( '../directives/hint-color/hint-color.directive' ) ; @ NgModule ( { declarations : [ SessionComponent , LoginComponent , HintColorDirective ] , exports : [ SessionComponent ] , imports : [ TNSFontIconModule . forRoot ( { 'fa' : 'font-awesome.css' } ) ] , providers : [ ] } ) export class SessionModule { }

Note that we’re using a require instead of the ES6 import. This is because of the dynamic nature of the platform specific declaration. We need to do it this way in order to avoid TypeScript compilation error indicating that the module is not found.

We can now use the directive inside the LoginComponent template:

<!-- app/session/login.component.html --> [...] <TextField hint="Login" [hintColor]="'#FFFFFF'"></TextField> <TextField hint="Password" [hintColor]="'#FFFFFF'"></TextField> [...] 1 2 3 4 5 6 <!-- app/session/login.component.html --> [...] <TextField hint = "Login" [ hintColor ] = "'#FFFFFF'" > </TextField> <TextField hint = "Password" [ hintColor ] = "'#FFFFFF'" > </TextField> [ . . . ]

We should now have our white TextField hints:



Create the Footer

As mentioned on the introduction, we want to be able to switch the current screen by tapping on the footer. Let’s start by creating its layout. Go back to the session.component.html file and edit its content like this:

<!-- app/session/session.component.html --> <GridLayout class="container" rows="*, auto"> <GridLayout row="0"> <StackLayout #loginWrapper> <login></login> </StackLayout> <StackLayout #registerWrapper> </StackLayout> </GridLayout> <StackLayout class="footer" row="1"> <Label class="footer-text" text="My Text"></Label> </StackLayout> </GridLayout> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <!-- app/session/session.component.html --> <GridLayout class = "container" rows = "*, auto" > <GridLayout row = "0" > <StackLayout # loginWrapper > <login> </login> </StackLayout> <StackLayout # registerWrapper > </StackLayout> </GridLayout> <StackLayout class = "footer" row = "1" > <Label class = "footer-text" text = "My Text" > </Label> </StackLayout> </GridLayout>

The footer text will be dynamically updated according to the screen currently displayed, so we just set it to “My Text” for now.

Next, add the following styling:

/* app/session/session.component.css */ [...] StackLayout.footer { border-color: rgba(255, 255, 255, 0.5); border-top-width: 1; } Label.footer-text { color: #FFFFFF; margin: 15; text-align: center; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 /* app/session/session.component.css */ [...] StackLayout.footer { border-color : rgba ( 255, 255, 255, 0.5 ) ; border-top-width : 1 ; } Label.footer-text { color : #FFFFFF ; margin : 15 ; text-align : center ; }

Create the RegisterComponent

First, create the empty component:

// app/session/register.component.ts import { Component } from '@angular/core'; @Component({ selector: 'register', templateUrl: 'session/register/register.component.html', styleUrls: ['session/session.component.css'] }) export class RegisterComponent { } 1 2 3 4 5 6 7 8 9 10 11 // app/session/register.component.ts import { Component } from '@angular/core' ; @ Component ( { selector : 'register' , templateUrl : 'session/register/register.component.html' , styleUrls : [ 'session/session.component.css' ] } ) export class RegisterComponent { }

Next, the template:

<!-- app/session/register/register.component.html --> <StackLayout> <StackLayout class="form-container"> <Label class="fa session-icon" [text]="'fa-user-plus' | fonticon"></Label> <TextField hint="Login" [hintColor]="'#FFFFFF'"></TextField> <TextField hint="Email" [hintColor]="'#FFFFFF'"></TextField> <TextField hint="Password" [hintColor]="'#FFFFFF'"></TextField> <TextField hint="Confirmation" [hintColor]="'#FFFFFF'"></TextField> <Button text="Register"></Button> </StackLayout> <Label class="caption" text="Forgot your password? tap here"></Label> </StackLayout> 1 2 3 4 5 6 7 8 9 10 11 12 13 <!-- app/session/register/register.component.html --> <StackLayout> <StackLayout class = "form-container" > <Label class = "fa session-icon" [ text ] = "'fa-user-plus' | fonticon" > </Label> <TextField hint = "Login" [ hintColor ] = "'#FFFFFF'" > </TextField> <TextField hint = "Email" [ hintColor ] = "'#FFFFFF'" > </TextField> <TextField hint = "Password" [ hintColor ] = "'#FFFFFF'" > </TextField> <TextField hint = "Confirmation" [ hintColor ] = "'#FFFFFF'" > </TextField> <Button text = "Register" > </Button> </StackLayout> <Label class = "caption" text = "Forgot your password? tap here" > </Label> </StackLayout>

Then, we can declare the RegisterComponent within SessionModule :

// app/session/session.module.ts [...] @NgModule({ declarations: [ SessionComponent, LoginComponent, RegisterComponent, HintColorDirective ], [...] 1 2 3 4 5 6 7 8 9 10 11 // app/session/session.module.ts [ . . . ] @ NgModule ( { declarations : [ SessionComponent , LoginComponent , RegisterComponent , HintColorDirective ] , [ . . . ]

To display the result, just comment out the #loginWrapper StackLayout in session.component.html, and add the register selector inside the #registerWrapper:

<!-- app/session/session.component.html --> [...] <!--<StackLayout #loginWrapper>--> <!--<login></login>--> <!--</StackLayout>--> <StackLayout #registerWrapper> <register></register> </StackLayout> [...] 1 2 3 4 5 6 7 8 9 10 <!-- app/session/session.component.html --> [...] <!--<StackLayout #loginWrapper>--> <!--<login></login>--> <!--</StackLayout>--> <StackLayout # registerWrapper > <register> </register> </StackLayout> [ . . . ]

which gives:



Ok, we’re now done with the template, let’s do something fun!

Animate the Screen Switching

Let’s add some animations to this static template. First, uncomment the #loginWrapper section in order to let the two StackLayouts visible. Then, open up session.component.ts and add the following content:

// app/session/session.component.ts import { Component, ViewChild, ElementRef, OnInit } from '@angular/core'; import { StackLayout } from 'ui/layouts/stack-layout'; import { screen } from 'platform'; @Component({ selector: 'session', templateUrl: 'session/session.component.html', styleUrls: ['session/session.component.css'] }) export class SessionComponent implements OnInit { @ViewChild('loginWrapper') loginWrapperRef: ElementRef; private get loginWrapper(): StackLayout { return this.loginWrapperRef.nativeElement; } @ViewChild('registerWrapper') registerWrapperRef: ElementRef; private get registerWrapper(): StackLayout { return this.registerWrapperRef.nativeElement; } private get screenWidth(): number { return screen.mainScreen.widthDIPs; } private screenToggled = false; public ngOnInit(): void { this.registerWrapper.translateX = this.screenWidth; } public toggleScreen(): void { const animationDuration = 400; if (!this.screenToggled) { this.loginWrapper.animate({ translate: { x: -this.screenWidth, y: 0 }, duration: animationDuration }); this.registerWrapper.animate({ translate: { x: 0, y: 0 }, duration: animationDuration }); } else { this.loginWrapper.animate({ translate: { x: 0, y: 0 }, duration: animationDuration }); this.registerWrapper.animate({ translate: { x: this.screenWidth, y: 0 }, duration: animationDuration }); } this.screenToggled = !this.screenToggled; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 // app/session/session.component.ts import { Component , ViewChild , ElementRef , OnInit } from '@angular/core' ; import { StackLayout } from 'ui/layouts/stack-layout' ; import { screen } from 'platform' ; @ Component ( { selector : 'session' , templateUrl : 'session/session.component.html' , styleUrls : [ 'session/session.component.css' ] } ) export class SessionComponent implements OnInit { @ ViewChild ( 'loginWrapper' ) loginWrapperRef : ElementRef ; private get loginWrapper ( ) : StackLayout { return this . loginWrapperRef . nativeElement ; } @ ViewChild ( 'registerWrapper' ) registerWrapperRef : ElementRef ; private get registerWrapper ( ) : StackLayout { return this . registerWrapperRef . nativeElement ; } private get screenWidth ( ) : number { return screen . mainScreen . widthDIPs ; } private screenToggled = false ; public ngOnInit ( ) : void { this . registerWrapper . translateX = this . screenWidth ; } public toggleScreen ( ) : void { const animationDuration = 400 ; if ( ! this . screenToggled ) { this . loginWrapper . animate ( { translate : { x : - this . screenWidth , y : 0 } , duration : animationDuration } ) ; this . registerWrapper . animate ( { translate : { x : 0 , y : 0 } , duration : animationDuration } ) ; } else { this . loginWrapper . animate ( { translate : { x : 0 , y : 0 } , duration : animationDuration } ) ; this . registerWrapper . animate ( { translate : { x : this . screenWidth , y : 0 } , duration : animationDuration } ) ; } this . screenToggled = ! this . screenToggled ; } }

Let’s break this down a little bit. Don’t worry about the code duplication for now, we’ll refactor this a bit later on.

First, the declarations:

[...] @ViewChild('loginWrapper') loginWrapperRef: ElementRef; private get loginWrapper(): StackLayout { return this.loginWrapperRef.nativeElement; } @ViewChild('registerWrapper') registerWrapperRef: ElementRef; private get registerWrapper(): StackLayout { return this.registerWrapperRef.nativeElement; } private get screenWidth(): number { return screen.mainScreen.widthDIPs; } private screenToggled = false; [...] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 [ . . . ] @ ViewChild ( 'loginWrapper' ) loginWrapperRef : ElementRef ; private get loginWrapper ( ) : StackLayout { return this . loginWrapperRef . nativeElement ; } @ ViewChild ( 'registerWrapper' ) registerWrapperRef : ElementRef ; private get registerWrapper ( ) : StackLayout { return this . registerWrapperRef . nativeElement ; } private get screenWidth ( ) : number { return screen . mainScreen . widthDIPs ; } private screenToggled = false ; [ . . . ]

We basically retrieve our two wrapper and add private getters in order to get the StackLayout objects out of them. We also declare a getter to get the actual screen width (using the screen module). This will be helpful to create the animations simulating the ‘out of the screen’ translations. The last one, screenToggled , is a flag indicating if the screen is toggled (from login, to register) or not.

Then, we have:

[...] public ngOnInit(): void { this.registerWrapper.translateX = this.screenWidth; } [...] 1 2 3 4 5 [ . . . ] public ngOnInit ( ) : void { this . registerWrapper . translateX = this . screenWidth ; } [ . . . ]

we translate the registerWrapper on the X-axis to the screen width, in order to take it out of the screen, to the right.

and finally:

[...] public toggleScreen(): void { animationDuration = 400; if (!this.screenToggled) { this.loginWrapper.animate({ translate: { x: -this.screenWidth, y: 0 }, duration: animationDuration }); this.registerWrapper.animate({ translate: { x: 0, y: 0 }, duration: animationDuration }); } else { this.loginWrapper.animate({ translate: { x: 0, y: 0 }, duration: animationDuration }); this.registerWrapper.animate({ translate: { x: this.screenWidth, y: 0 }, duration: animationDuration }); } this.screenToggled = !this.screenToggled; } [...] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 [ . . . ] public toggleScreen ( ) : void { animationDuration = 400 ; if ( ! this . screenToggled ) { this . loginWrapper . animate ( { translate : { x : - this . screenWidth , y : 0 } , duration : animationDuration } ) ; this . registerWrapper . animate ( { translate : { x : 0 , y : 0 } , duration : animationDuration } ) ; } else { this . loginWrapper . animate ( { translate : { x : 0 , y : 0 } , duration : animationDuration } ) ; this . registerWrapper . animate ( { translate : { x : this . screenWidth , y : 0 } , duration : animationDuration } ) ; } this . screenToggled = ! this . screenToggled ; } [ . . . ]

We use this method to trigger the screen change animation. We check the screenToggled flag. If we haven’t toggled yet (we’re on the initial screen, so the login screen), then we animate the loginWrapper to translate it to the left, to make it out of the screen (hence -this.screenWidth here). We bring at the same time (animate being asynchronous) the registerWrapper within the screen, at the initial position (x = 0). If the screen is already toggled, we bring the loginWrapper back to the screen, and we throw the registerWrapper away to the right of the screen. Finally, we change the flag value.

We now need to hook up this method to the (tap) event of the footer StackLayout:

<!-- app/session/session.component.html --> [...] <StackLayout (tap)="toggleScreen()" class="footer" row="1"> <Label class="footer-text" text="My Text"></Label> </StackLayout> [...] 1 2 3 4 5 6 7 <!-- app/session/session.component.html --> [...] <StackLayout ( tap ) = "toggleScreen()" class = "footer" row = "1" > <Label class = "footer-text" text = "My Text" > </Label> </StackLayout> [ . . . ]

And let’s see this in action:

Before we move on, let’s refactor this a bit:

[...] public toggleScreen(): void { if (!this.screenToggled) { this.translateToTheLeftOfTheScreen(this.loginWrapper); this.bringInsideTheScreen(this.registerWrapper); } else { this.bringInsideTheScreen(this.loginWrapper); this.translateToTheRightOfTheScreen(this.registerWrapper); } this.screenToggled = !this.screenToggled; } private bringInsideTheScreen(wrapper: StackLayout) { this.translateWrapper(wrapper, 0); } private translateToTheRightOfTheScreen(wrapper: StackLayout) { this.translateWrapper(wrapper, this.screenWidth); } private transaletToTheLeftOfTheScreen(wrapper: StackLayout) { this.translateWrapper(wrapper, -this.screenWidth); } private translateWrapper(wrapper: StackLayout, x: number) { const animationDuration = 400; wrapper.animate({ translate: { x: x, y: 0 }, duration: animationDuration }); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 [ . . . ] public toggleScreen ( ) : void { if ( ! this . screenToggled ) { this . translateToTheLeftOfTheScreen ( this . loginWrapper ) ; this . bringInsideTheScreen ( this . registerWrapper ) ; } else { this . bringInsideTheScreen ( this . loginWrapper ) ; this . translateToTheRightOfTheScreen ( this . registerWrapper ) ; } this . screenToggled = ! this . screenToggled ; } private bringInsideTheScreen ( wrapper : StackLayout ) { this . translateWrapper ( wrapper , 0 ) ; } private translateToTheRightOfTheScreen ( wrapper : StackLayout ) { this . translateWrapper ( wrapper , this . screenWidth ) ; } private transaletToTheLeftOfTheScreen ( wrapper : StackLayout ) { this . translateWrapper ( wrapper , - this . screenWidth ) ; } private translateWrapper ( wrapper : StackLayout , x : number ) { const animationDuration = 400 ; wrapper . animate ( { translate : { x : x , y : 0 } , duration : animationDuration } ) ; } }

At the very end, we create a translateWrapper() method that takes a StackLayout in input, as well as an x position. We then call the animate method on the wrapper, and pass the given x value. we don’t need to pass any y value since the vertical position will stay the same anyway (0). We then use this method to build up three new ones: bringInsideTheScreen() (leading to x = 0), translateToTheRightOfTheScreen() (x = screenWidth) and translateToTheLeftOfTheScreen() (x = – screenWidth).

Let’s now work on the animation of the footer text.

Fade In/Out the Footer Text

For the footer, we’re going to use a dynamic text, depending on wether the screen is toggled or not. Let’s first edit the template:

<!-- app/session/session.component.ts --> [...] <StackLayout (tap)="toggleScreen()" class="footer" row="1"> <Label #footerLabel class="footer-text" [text]="footerText"></Label> </StackLayout> 1 2 3 4 5 6 <!-- app/session/session.component.ts --> [...] <StackLayout ( tap ) = "toggleScreen()" class = "footer" row = "1" > <Label # footerLabel class = "footer-text" [ text ] = "footerText" > </Label> </StackLayout>

This way, we hook up the text attribute of the Label to the value of a footerText Property that we will define in the Component.

Next, add the following lines to the session.component.ts :

// app/session/session.component.ts [...] @ViewChild('footerLabel') footerLabelRef: ElementRef; private get footerLabel(): Label { return this.footerLabelRef.nativeElement; } public footerText: string; private get registerText(): string { return 'No account yet? Tap here to register'; } private get loginText(): string { return 'Already registered? Tap here to login'; } [...] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // app/session/session.component.ts [ . . . ] @ ViewChild ( 'footerLabel' ) footerLabelRef : ElementRef ; private get footerLabel ( ) : Label { return this . footerLabelRef . nativeElement ; } public footerText : string ; private get registerText ( ) : string { return 'No account yet? Tap here to register' ; } private get loginText ( ) : string { return 'Already registered? Tap here to login' ; } [ . . . ]

We’ve also added two getters representing the register and login displayed texts. Let’s now edit the toggleScreen() method to handle the footer toggle:

[...] public toggleScreen(): void { if (!this.screenToggled) { this.translateToTheLeftOfTheScreen(this.loginWrapper); this.bringInsideTheScreen(this.registerWrapper); this.toggleFooter(this.loginText); } else { this.bringInsideTheScreen(this.loginWrapper); this.translateToTheRightOfTheScreen(this.registerWrapper); this.toggleFooter(this.registerText); } this.screenToggled = !this.screenToggled; } [...] private toggleFooter(newText: string) { const animationDuration = 200; this.footerLabel.animate({ opacity: 0, duration: animationDuration }).then(() => { this.footerText = newText; this.footerLabel.animate({ opacity: 1, duration: animationDuration }); }); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 [ . . . ] public toggleScreen ( ) : void { if ( ! this . screenToggled ) { this . translateToTheLeftOfTheScreen ( this . loginWrapper ) ; this . bringInsideTheScreen ( this . registerWrapper ) ; this . toggleFooter ( this . loginText ) ; } else { this . bringInsideTheScreen ( this . loginWrapper ) ; this . translateToTheRightOfTheScreen ( this . registerWrapper ) ; this . toggleFooter ( this . registerText ) ; } this . screenToggled = ! this . screenToggled ; } [ . . . ] private toggleFooter ( newText : string ) { const animationDuration = 200 ; this . footerLabel . animate ( { opacity : 0 , duration : animationDuration } ) . then ( ( ) = > { this . footerText = newText ; this . footerLabel . animate ( { opacity : 1 , duration : animationDuration } ) ; } ) ; }

The toggleFooter() method takes a string in input. We first animate the footerLabel to set its opacity to 0 (fade out), then change the footerText to the given newText , and finally, fade in the label. Notice that this time, we do the animations sequentially. We use a duration that is twice as short as the screen animation, so that it finishes exactly when the toggle is over (we have two animations here, the fade out, and the fade in).

Let’s see the result:



And again, let’s do a bit of refactoring:

[...] private toggleFooter(newText: string) { this.fadeOutFooterText() .then(() => { this.footerText = newText; this.fadeInFooterText(); }); } private fadeOutFooterText() { return this.fadeFooterTextTo(0); } private fadeInFooterText() { return this.fadeFooterTextTo(1); } private fadeFooterTextTo(opacity: number) { const animationDuration = 200; return this.footerLabel.animate({ opacity: opacity, duration: animationDuration }); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 [ . . . ] private toggleFooter ( newText : string ) { this . fadeOutFooterText ( ) . then ( ( ) = > { this . footerText = newText ; this . fadeInFooterText ( ) ; } ) ; } private fadeOutFooterText ( ) { return this . fadeFooterTextTo ( 0 ) ; } private fadeInFooterText ( ) { return this . fadeFooterTextTo ( 1 ) ; } private fadeFooterTextTo ( opacity : number ) { const animationDuration = 200 ; return this . footerLabel . animate ( { opacity : opacity , duration : animationDuration } ) ; } }

in the fadeFooterTextTo() method, we need to return the result of animate() (which is a JavaScript Promise ), since we use it to chain the fades.

Before we move on, let’s also create a getter to isolate the screen toggle animation duration:

[...] private get screenToggleDuration(): number { return 400; } [...] private translateWrapper(wrapper: StackLayout, x: number) { wrapper.animate({ translate: { x: x, y: 0 }, duration: this.screenToggleDuration }); } [...] 1 2 3 4 5 6 7 8 9 10 11 [ . . . ] private get screenToggleDuration ( ) : number { return 400 ; } [ . . . ] private translateWrapper ( wrapper : StackLayout , x : number ) { wrapper . animate ( { translate : { x : x , y : 0 } , duration : this . screenToggleDuration } ) ; } [ . . . ]

We also said that the fading animation duration should be half of the screen toggle duration, so let’s update the corresponding method:

[...] private fadeFooterTextTo(opacity: number) { return this.footerLabel.animate({ opacity: opacity, duration: this.screenToggleDuration / 2 }); } [...] 1 2 3 4 5 6 7 8 [ . . . ] private fadeFooterTextTo ( opacity : number ) { return this . footerLabel . animate ( { opacity : opacity , duration : this . screenToggleDuration / 2 } ) ; } [ . . . ]

We’re now done for the animation. Let’s now make the screen look a bit nicer.

Add a Neat Gradient Background

Let’s add a gradient background, cause that’s what cool kids do nowadays. By the time I’m writing this tutorial, NativeScript doesn’t support the gradient in CSS (but at the pace they bring in cool features, these lines might become obsolete very quickly. This means that we need to attack the native APIs. We’ll use the same pattern as for the HintColorDirective .

First, we’ll install the platform declarations:

npm install --save tns-platform-declarations@next 1 npm install -- save tns - platform - declarations @ next

Then modify references.d.ts to add the platform references:

/// <reference path="./node_modules/tns-core-modules/tns-core-modules.es2016.d.ts" /> /// <reference path="./node_modules/tns-platform-declarations/ios.d.ts" /> /// <reference path="./node_modules/tns-platform-declarations/android.d.ts" /> 1 2 3 4 /// <reference path="./node_modules/tns-core-modules/tns-core-modules.es2016.d.ts" /> /// <reference path="./node_modules/tns-platform-declarations/ios.d.ts" /> /// <reference path="./node_modules/tns-platform-declarations/android.d.ts" />

According to this link, we also need to update the tsconfig.json in order to avoid TypeScript compilation errors related to the platform definitions:

// tsconfig.json { "compilerOptions": { "module": "commonjs", "target": "es5", "experimentalDecorators": true, "lib": [ "es2016" ] }, "include": [ "typings-i386/*", "Interop.d.ts" ], "exclude": [ "node_modules", "platforms" ] } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 // tsconfig.json { "compilerOptions" : { "module" : "commonjs" , "target" : "es5" , "experimentalDecorators" : true , "lib" : [ "es2016" ] } , "include" : [ "typings-i386/*" , "Interop.d.ts" ] , "exclude" : [ "node_modules" , "platforms" ] }

Now, let’s go ahead and create the gradient-background.base.directive.ts :

// app/directives/gradient-background/gradient-background.base.directive.ts import { ElementRef, Input } from '@angular/core'; import { Layout } from 'ui/layouts/layout'; import { Color } from 'color'; export abstract class GradientBackgroundBaseDirective { constructor(private el: ElementRef) {} @Input() set gradientBackground(value: Array<string>) { const layout = <Layout>this.el.nativeElement; this.setGradientBackground(layout, value.map((v) => new Color(v))); } protected abstract setGradientBackground(view: Layout, colors: Array<Color>); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // app/directives/gradient-background/gradient-background.base.directive.ts import { ElementRef , Input } from '@angular/core' ; import { Layout } from 'ui/layouts/layout' ; import { Color } from 'color' ; export abstract class GradientBackgroundBaseDirective { constructor ( private el : ElementRef ) { } @ Input ( ) set gradientBackground ( value : Array < string > ) { const layout = < Layout > this . el . nativeElement ; this . setGradientBackground ( layout , value . map ( ( v ) = > new Color ( v ) ) ) ; } protected abstract setGradientBackground ( view : Layout , colors : Array < Color > ) ; }

Next, create the gradient-background.directive.android.ts file, hosting the Android native implementation:

// app/directives/gradient-background/gradient-background.directive.android.ts import { Directive, ElementRef } from '@angular/core'; import { Layout } from 'ui/layouts/layout'; import { Color } from 'color'; import { GradientBackgroundBaseDirective } from './gradient-background.base.directive'; @Directive({ selector: '[gradientBackground]' }) export class GradientBackgroundDirective extends GradientBackgroundBaseDirective { constructor(el: ElementRef) { super(el); } protected setGradientBackground(view: Layout, colors: Array<Color>) { let backgroundDrawable = new android.graphics.drawable.GradientDrawable(); let nativeColors = colors.map(c => c.android); backgroundDrawable.setColors(nativeColors); backgroundDrawable.setGradientType(0); // Linear Gradient let orientation = android.graphics.drawable.GradientDrawable.Orientation. TOP_BOTTOM; backgroundDrawable.setOrientation(orientation); view.android.setBackgroundDrawable(backgroundDrawable); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 // app/directives/gradient-background/gradient-background.directive.android.ts import { Directive , ElementRef } from '@angular/core' ; import { Layout } from 'ui/layouts/layout' ; import { Color } from 'color' ; import { GradientBackgroundBaseDirective } from './gradient-background.base.directive' ; @ Directive ( { selector : '[gradientBackground]' } ) export class GradientBackgroundDirective extends GradientBackgroundBaseDirective { constructor ( el : ElementRef ) { super ( el ) ; } protected setGradientBackground ( view : Layout , colors : Array < Color > ) { let backgroundDrawable = new android . graphics . drawable . GradientDrawable ( ) ; let nativeColors = colors . map ( c = > c . android ) ; backgroundDrawable . setColors ( nativeColors ) ; backgroundDrawable . setGradientType ( 0 ) ; // Linear Gradient let orientation = android . graphics . drawable . GradientDrawable . Orientation . TOP_BOTTOM ; backgroundDrawable . setOrientation ( orientation ) ; view . android . setBackgroundDrawable ( backgroundDrawable ) ; } }

And the gradient-background.directive.ios.ts for the iOS implementation:

// app/directives/gradient-background/gradient-background.directive.ios.ts import { Directive, ElementRef } from '@angular/core'; import { Layout } from 'ui/layouts/layout'; import { Color } from 'color'; import { GradientBackgroundBaseDirective } from './gradient-background.base.directive'; @Directive({ selector: '[gradientBackground]' }) export class GradientBackgroundDirective extends GradientBackgroundBaseDirective { constructor(el: ElementRef) { super(el); } protected setGradientBackground(view: Layout, colors: Array<Color>) { let nativeColors = NSMutableArray.alloc().initWithCapacity(colors.length); colors.forEach((c) => { nativeColors.addObject(interop.types.id(c.ios.CGColor)); }); let gradientLayer = CAGradientLayer.layer(); gradientLayer.colors = nativeColors; gradientLayer.frame = view.page.ios.view.bounds; view.ios.layer.insertSublayerAtIndex(gradientLayer, 0); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 // app/directives/gradient-background/gradient-background.directive.ios.ts import { Directive , ElementRef } from '@angular/core' ; import { Layout } from 'ui/layouts/layout' ; import { Color } from 'color' ; import { GradientBackgroundBaseDirective } from './gradient-background.base.directive' ; @ Directive ( { selector : '[gradientBackground]' } ) export class GradientBackgroundDirective extends GradientBackgroundBaseDirective { constructor ( el : ElementRef ) { super ( el ) ; } protected setGradientBackground ( view : Layout , colors : Array < Color > ) { let nativeColors = NSMutableArray . alloc ( ) . initWithCapacity ( colors . length ) ; colors . forEach ( ( c ) = > { nativeColors . addObject ( interop . types . id ( c . ios . CGColor ) ) ; } ) ; let gradientLayer = CAGradientLayer . layer ( ) ; gradientLayer . colors = nativeColors ; gradientLayer . frame = view . page . ios . view . bounds ; view . ios . layer . insertSublayerAtIndex ( gradientLayer , 0 ) ; } }

It’s important to note that we’re using a workaround here: this iOS implementation uses the dimensions of the whole page ( view.page.ios.view.bounds ) to create the gradient, and not the ones from the given view. This is because NativeScript provides us with the measured dimensions only late in the startup process (event after the AfterViewInit hook), which makes it difficult to synchronise the application of the gradient and the required bounds to display it. We don’t have this problem with Android because the implementation, because it doesn’t directly rely on the dimensions, but on the view itself.

In our use case, this isn’t a problem since we’re using it as a global background anyway, but it might be one if you plan to reuse this directive to fill only a portion of the screen.

Let’s reference the Directive within the SessionModule :

// app/session/session.module.ts [...] const { GradientBackgroundDirective } = require('../directives/gradient-background/gradient-background.directive'); @NgModule({ declarations: [ SessionComponent, LoginComponent, RegisterComponent, HintColorDirective, GradientBackgroundDirective ], [...] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // app/session/session.module.ts [ . . . ] const { GradientBackgroundDirective } = require ( '../directives/gradient-background/gradient-background.directive' ) ; @ NgModule ( { declarations : [ SessionComponent , LoginComponent , RegisterComponent , HintColorDirective , GradientBackgroundDirective ] , [ . . . ]

Now we can use the Directive to create the gradient with any number of colors that we want (try to add a third one!):

<!-- app/session/session.component.html --> <GridLayout [gradientBackground]="['#7319b1', '#13b3f0']" class="container" rows="*, auto"> <GridLayout row="0"> <StackLayout #loginWrapper> <login></login> </StackLayout> <StackLayout #registerWrapper> <register></register> </StackLayout> </GridLayout> <StackLayout (tap)="toggleScreen()" class="footer" row="1"> <Label #footerLabel class="footer-text" [text]="footerText"></Label> </StackLayout> </GridLayout> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <!-- app/session/session.component.html --> <GridLayout [ gradientBackground ] = "['#7319b1', '#13b3f0']" class = "container" rows = "*, auto" > <GridLayout row = "0" > <StackLayout # loginWrapper > <login> </login> </StackLayout> <StackLayout # registerWrapper > <register> </register> </StackLayout> </GridLayout> <StackLayout ( tap ) = "toggleScreen()" class = "footer" row = "1" > <Label # footerLabel class = "footer-text" [ text ] = "footerText" > </Label> </StackLayout> </GridLayout>

Our screen should now look like this:

That’s it ! I hope you found this tutorial useful, and if it’s the case, go ahead and share it 🙂

Don’t hesitate to write down a comment if you have any trouble.

Related

This entry was posted in Angular2 NativeScript and tagged android nativescript . Bookmark the permalink