我想知道是否有人可以帮助解释为什么我不能动态改变表单输入类型?
例如
<user-input type="{{ isActive ? 'password' : 'text' }}"></user-input>
不起作用。
但这是可行的,
<user-input type="password" *ngIf="isActive"></user-input>
<user-input type="text" *ngIf="!isActive"></user-input>
user-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
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();
}
}
}
我遇到的问题是,当我动态设置类型时,user-input-password指令不会被触发。如果我直接将type设置为password,那么它就会被触发。
有没有其他动态改变输入类型的方法?
发布于 2018-04-03 13:24:53
尝尝这个
<user-input [type]="isActive ? 'password' : 'text'"></user-input>
请看一下这个
Dynamically generate input field type with angular 2 and set the type of the field
发布于 2018-04-03 13:27:11
你可以选择这种方式。工作时间最长:
<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';
}
发布于 2018-04-03 13:30:06
我建议从typescript中处理这个问题,比如
type: string;
functiontochangetype(){
if(your condtion ){
this.type="password";
}else{
this.type="text"
}
}
和HTML格式
<user-input type={{type}}></user-input>
https://stackoverflow.com/questions/49622750
复制相似问题