简体   繁体   English

Angular2 - 无法动态更改输入类型

[英]Angular2 - cannot change input type dynamically

I was wondering if anyone can help explain why i am unable to change form input type dynamically? 我想知道是否有人可以帮助解释为什么我无法动态更改表单输入类型?

For eg 例如

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

doesn't work. 不起作用。

But this works, 但这有效,

<user-input type="password" *ngIf="isActive"></user-input>
<user-input type="text" *ngIf="!isActive"></user-input>

user-input.ts 用户input.ts

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

@Component({
    selector: 'user-input',
    templateUrl: './user-input.html'
})
export class UserInput {

    @Input()
    public isActive: boolean;

    constructor() {

    }
}

user-input.html 用户input.html

<input 
    type="{{ isActive ? 'password' : 'text' }}" 
    class="form-control"
    [(ngModel)]="value"
/>
user-input-password.ts

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

@Directive({
  selector:
      'input[type=password][formControlName],input[type=password][formControl],input[type=password][ngModel]'
})
export class PasswordValueAccessor {

    public pattern: RegExp;

    private regexMap = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/;

    @HostListener('keypress', ['$event']) 
    public onKeyPress (e: any)
    {
        this.pattern = this.regexMap;
        const inputChar = e.key;

        if (this.pattern.test(inputChar)) {
            // success
        } else {
            e.preventDefault();
        }
    }
}

The issue i have is that when i set the type dynamically, the user-input-password directive doesn't get triggered. 我遇到的问题是,当我动态设置类型时,不会触发user-input-password指令。 If i set the type to password directly then it does get trigged. 如果我直接将类型设置为密码,那么它会被触发。

Is there another way to dynamically change input type? 还有另一种动态改变输入类型的方法吗?

try this 尝试这个

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

Please take a look at this 请看一下这个

Dynamically generate input field type with angular 2 and set the type of the field 动态生成角度为2的输入字段类型并设置字段的类型

You can prefer this way. 你可以这样喜欢。 works most time: 工作时间最多:

<user-input #input type="password" ></user-input>
<button (click)="changeInput(input)">Change input</button>

ts file ts文件

changeInput(input: any): any {
    input.type = input.type === 'password' ? 'text' : 'password';
  }

I would suggest to handle this from typescript like 我建议从打字稿中处理这个问题

type: string;

functiontochangetype(){
if(your condtion ){
this.type="password";
}else{
this.type="text"
}
}

and in HTML 并在HTML中

<user-input type={{type}}></user-input>

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

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