简体   繁体   中英

Changing input type=“tel” to password field using Angular 2/Ionic 2

I want to change the input type tel to password field using Angular 2/Ionic 2.

I have a pin number field which will take number as input and I want to change the number to password field once the keypress event trigger.

I tried in the following way but the keypad is closing after enter the first number.

import { Component, Directive, HostListener } from '@angular/core';

  @Directive({
      selector: '.inputmask'
    })    
    export class MyDirective {
       @HostListener('document:keyup', ['$event.target'])
        onFocus(target) {
          target.type = 'password';
        }
        /*@HostListener('focusout', ['$event.target'])
        onFocusout(target) {
          target.type = 'tel';
        }*/
    }

And my template:

<ion-input type="tel" [formControl]="aadhaarno" class="inputmask">

This seems like a perfect use for ViewChild . It can be used to get reference to HTML element from DOM in your component so you can alter it. First, you need to add template variable to input element which will be used to get reference to it:

<ion-input #myInput type="tel" [formControl]="aadhaarno" class="inputmask">

Then in your component you have to import ViewChild and use it to get reference to input element in DOM:

import { ViewChild } from '@angular/core';

@ViewChild('myInput')
myInput: any;

Then you create a function which will use myInput variable (it now has reference to input) to change its type to password and call it somewhere:

changeInput() {
this.myInput.nativeElement.type = "password";
}

Here's working Plunker .

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