Tecnico Tecnico - 3 months ago 38
TypeScript Question

Floating label, How to get a result in .ts?

I have a simple question but I can't resolve it. I have a floating label in my .html like this:

<ion-label floating >Username</ion-label>
<ion-input type="text" ></ion-input>


<ion-label floating>Password</ion-label>
<ion-input type="password"></ion-input>

How can I get username and password in my .ts file?
Thanks in advance!

Best regards.


You should use ngModel like you can see in Angular docs

     <ion-label floating >Username</ion-label>
     <ion-input [(ngModel)]="username" name="username" type="text" ></ion-input>

     <ion-label floating>Password</ion-label>
     <ion-input [(ngModel)]="password" name="password" type="password"></ion-input>

And in your .ts code:

export class HomePage {

  private username: string;
  private password: string;

  constructor() { 


So in the code you can use the username and password properties to access the values the user entered in the view. Please take a look at Angular 2 docs to learn more about this and some other topics related to forms.


Since Ionic 2-beta.11 uses the new Angular Forms, you would need to check a few additional things to make it work:

First, please check the dependencies in you package.json file, to be sure you have something like this:

"@angular/common": "2.0.0-rc.4",
"@angular/compiler": "2.0.0-rc.4",
"@angular/core": "2.0.0-rc.4",
"@angular/forms": "0.2.0",
"@angular/http": "2.0.0-rc.4",
"@angular/platform-browser": "2.0.0-rc.4",
"@angular/platform-browser-dynamic": "2.0.0-rc.4",
"es6-shim": "^0.35.0",
"ionic-angular": "2.0.0-beta.11",
"ionic-native": "1.3.10",
"ionicons": "3.0.0",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.6",
"zone.js": "0.6.12"

It may be slightly different, but the important thing is that the angular stuff uses the 2.0.0-rc.4 version, and also that the "@angular/forms": "0.2.0", dependency is included.

Then, in your app.ts file you have to import

import { disableDeprecatedForms, provideForms } from '@angular/forms';

And in your ionicBootstrap call those methods to disable the deprecated forms, and enable the new forms module instead

    disableDeprecatedForms(),  // disable deprecated forms
    provideForms()             // enable new forms module
  ], {});

And then, in the page where you have the form, just import things related to forms from @angular/forms. Please check that you don't import things related to forms from other any module (like @angular/core).

import { FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES } from '@angular/forms';