首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Angular2 -无法动态更改输入类型

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

Stack Overflow用户
提问于 2018-04-03 13:20:56
回答 4查看 13.5K关注 0票数 6

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

例如

代码语言:javascript
运行
复制
<user-input type="{{ isActive ? 'password' : 'text' }}"></user-input>

不起作用。

但这是可行的,

代码语言:javascript
运行
复制
<user-input type="password" *ngIf="isActive"></user-input>
<user-input type="text" *ngIf="!isActive"></user-input>

user-input.ts

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
<input 
    type="{{ isActive ? 'password' : 'text' }}" 
    class="form-control"
    [(ngModel)]="value"
/>
代码语言:javascript
运行
复制
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();
        }
    }
}

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

有没有其他动态改变输入类型的方法?

EN

回答 4

Stack Overflow用户

发布于 2018-04-03 13:24:53

尝尝这个

代码语言:javascript
运行
复制
<user-input [type]="isActive ? 'password' : 'text'"></user-input>

请看一下这个

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

票数 17
EN

Stack Overflow用户

发布于 2018-04-03 13:27:11

你可以选择这种方式。工作时间最长:

代码语言:javascript
运行
复制
<user-input #input type="password" ></user-input>
<button (click)="changeInput(input)">Change input</button>

ts文件

代码语言:javascript
运行
复制
changeInput(input: any): any {
    input.type = input.type === 'password' ? 'text' : 'password';
  }
票数 3
EN

Stack Overflow用户

发布于 2018-04-03 13:30:06

我建议从typescript中处理这个问题,比如

代码语言:javascript
运行
复制
type: string;

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

和HTML格式

代码语言:javascript
运行
复制
<user-input type={{type}}></user-input>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49622750

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档