【问题标题】:Changing input type="tel" to password field using Angular 2/Ionic 2使用 Angular 2/Ionic 2 将输入类型 =“tel”更改为密码字段
【发布时间】:2017-03-09 23:16:34
【问题描述】:

我想使用 Angular 2/Ionic 2 将输入类型 tel 更改为 password 字段。

我有一个将数字作为输入的密码字段,我想在按键事件触发后将数字更改为密码字段。

我尝试了以下方式,但键盘在输入第一个数字后关闭。

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';
        }*/
    }

还有我的模板:

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

【问题讨论】:

    标签: angular ionic2 angular2-template angular2-forms


    【解决方案1】:

    这似乎是ViewChild 的完美用途。它可用于从组件中的 DOM 获取对 HTML 元素的引用,以便您可以更改它。首先,您需要将模板变量添加到输入元素,用于获取对它的引用:

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

    然后在您的组件中,您必须导入 ViewChild 并使用它来获取对 DOM 中输入元素的引用:

    import { ViewChild } from '@angular/core';
    
    @ViewChild('myInput')
    myInput: any;
    

    然后您创建一个函数,该函数将使用myInput 变量(它现在具有对输入的引用)将其类型更改为password 并在某处调用它:

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

    这里是working Plunker

    【讨论】:

    • 你不应该直接使用原生元素。您应该使用渲染器服务。你可以在这里阅读google.co.il/…为什么
    • @PatrickJane 如果我理解正确,如果您正在开发浏览器应用程序,直接使用nativeElement 是完全可以的。 The problem with this approach is that when we access the native element directly we are giving up on Angular’s DOM abstraction and miss out on the opportunity to be able to execute also in none-DOM environments such as: native mobile, native desktop, web worker or server side rendering. Remember that Angular is a platform, and the browser is just one option for where we can render our app.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 2020-07-14
    • 1970-01-01
    相关资源
    最近更新 更多