简体   繁体   中英

How to dynamically change the type of an input field in ionic2/Angular2?

I am trying to implement a password field with a reveal option

<ion-item>
  <ion-label color="dark" fixed>Mot De Passe</ion-label>
  <ion-input type="password"></ion-input>
  <ion-icon
      [name]="isActive?'eye':'eye-off'"
      item-right
      (click)="isActive=!isActive;"
      isActive=true>
 </ion-icon>
</ion-item>

So, I can change the icon but I can't figure out how to toggle the type of the password field !!

You have a few options

Interpolation

<ion-input type="{{ isActive ? 'password' : 'text' }}"></ion-input>

or

Property Binding

<ion-input [type]="isActive ? 'password' : 'text'"></ion-input>

You can use Property binding to pass a string such as 'text' or 'password' value to the type attribute of the input element:

export class SomePage {
    type: string = "text";
    isActive: Boolean = false; 

    constructor() {}

    getType() {
        return isActive ? 'password' : 'text';
    }

    setType() {
        this.type = isActive ? 'password' : 'text';
    }
}

<ion-item>
  <ion-label color="dark" fixed>Mot De Passe</ion-label>
  <ion-input [type]="type"></ion-input>
  <ion-input [type]="getType()"></ion-input>
  <ion-icon
      [name]="isActive ? 'eye' : 'eye-off'"
      item-right
      (click)="isActive = !isActive;"
      isActive=true>
 </ion-icon>
</ion-item>

You can change the value to however you would need either through the ternary statements you are using isActive ? 'password':'text' isActive ? 'password':'text' or perhaps a method that sets the string value to move the logic out of the template and into the controller.

Here is a plunker demonstrating the functionality showing both setting equal to a class string property and ternary statement.

HTML File :

<input type="{{isPassword ? 'password' : 'text' }}">
<button type="button" (click)="show()">show password</button>

TS File :

isPassword = true;
show() {
    this.isPassword = !(this.isPassword);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM