我想知道是否有人可以帮助解释为什么我无法动态更改表单输入类型?
例如
<user-input type="{{ isActive ? 'password' : 'text' }}"></user-input>
没用。
但这行得通,
<user-input type="password" *ngIf="isActive"></user-input>
<user-input type="text" *ngIf="!isActive"></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() {
}
}
用户输入.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 #input type="password" ></user-input>
<button (click)="changeInput(input)">Change input</button>
ts文件
changeInput(input: any): any {
input.type = input.type === 'password' ? 'text' : 'password';
}
我建议像
这样的打字稿来处理这个问题type: string;
functiontochangetype(){
if(your condtion ){
this.type="password";
}else{
this.type="text"
}
}
和 HTML
<user-input type={{type}}></user-input>
我正在遍历一个具有多个键值对的对象并动态显示“标签”和“值”(在这里,我无法决定哪个键将是
"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
希望这有帮助。谢谢!
将输入类型直接绑定到输入元素不起作用,但将条件添加到父元素有效。代码如下:
<div *ngIf="input.type === 'number' ">
<input type="number">
</div>
<div *ngIf="inpyt.type === 'text' ">
<input type="text">
</div>