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

时间:2018-04-03 05:20:56

标签: angular input angular2-forms angular-forms form-control

我想知道是否有人可以帮助解释为什么我无法动态更改表单输入类型?

例如

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

不起作用。

但这很有效,

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

用户input.ts

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

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

    @Input()
    public isActive: boolean;

    constructor() {

    }
}

用户input.html

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

用户输入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();
        }
    }
}

我遇到的问题是,当我动态设置类型时,不会触发user-input-password指令。如果我直接将类型设置为密码,那么它就会被触发。

还有另一种动态更改输入类型的方法吗?

提前致谢..

4 个答案:

答案 0 :(得分:4)

试试这个

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

请看一下

Dynamically generate input field type with angular 2 and set the type of the field

答案 1 :(得分:1)

你可以这样喜欢。工作时间最长:

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

ts文件

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

答案 2 :(得分:0)

我建议从打字稿中处理这个,比如

type: string;

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

和HTML

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

答案 3 :(得分:0)

我正在遍历具有多个键值对的对象并动态显示“标签”和“值”(在这里,我无法决定哪个键将是 "password")。因此,我使用了最终对我有用的属性绑定 type,而不是 [type] 属性。

这是我的代码

<div class="form-group row" *ngFor="let item of allItemsObject | keyvalue">
    <label for={{item.key}} class="col-sm-5 col-form-label">{{item.key | uppercase}}</label>
    <div class="col-sm-7">
        <input [type]="item?.key==='password'?'password':'text'" class="form-control" id={{item.key}} value={{item.value}} />
    </div>
</div>

这可以帮助查询(想知道如何遍历对象以动态打印键值)以及下一步如何动态更新 "type" property value of <input/> tag

希望这会有所帮助。谢谢!

相关问题