简体   繁体   English

使用Angular 2 / Ionic 2将输入类型=“tel”更改为密码字段

[英]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. 我想使用Angular 2 / Ionic 2将输入类型tel更改为password字段。

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 . 这似乎是ViewChild的完美用法。 It can be used to get reference to HTML element from DOM in your component so you can alter it. 它可用于从组件中的DOM引用HTML元素,以便您可以更改它。 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: 然后在组件中,您必须导入ViewChild并使用它来获取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: 然后你创建一个函数,它将使用myInput变量(它现在引用了输入)将其类型更改为password并在某处调用它:

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

Here's working Plunker . 这是工作的Plunker

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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