[英]How to convert input field type=“password” to type=“text” in angular?
您能否告诉我如何将输入字段type =“ password”转换为angular的type =“ text”。在我的演示中,我有两个输入字段Mobile no
和Re-enter mobile number
如果用户输入相同的10
位数字,它将type =“ password”转换为type =“ text”
例如:如果您输入手机号码9891234567
然后重新输入密码9891234567
则两个字段都将转换为type =“ text”。 我们可以在Angular中实现吗?
这是我的代码https://stackblitz.com/edit/angular-jfqkfo?file=src%2Fapp%2Fapp.component.ts
import { Component } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
cfForm: FormGroup;
constructor(private fb: FormBuilder){
this.cfForm = this.fb.group({
mobile_no: ['', [Validators.required, Validators.pattern('^[0-9]{10}$')]],
re_mobile_no: ['', [Validators.required, Validators.pattern('^[0-9]{10}$')]],
});
}
}
我可以在jQuery中使用$('id')。attr('type','text') ; 但是我将如何在Angular中做
只需将输入类型属性绑定到cfForm.valid布尔值即可。
<input [type]="cfForm.valid ? 'text' : 'password'" />
然后,组件中的逻辑会将值从false更改为true,并且输入类型将更改。
您可以尝试使用[type]
我在Stackblitz上创建了演示
<input NumbersOnly="true" [type]="cfForm.get('mobile_no').value.length==10 && cfForm.get('mobile_no').value==cfForm.get('re_mobile_no').value ? 'text' : 'password'" placeholder="Enter Mobile no" formControlName="mobile_no" maxlength="10">
这应该对您有用:监听表单值的更改,如果值匹配,则更改输入的类型
this.cfForm.valueChanges.subscribe(value => {
if (value.mobile_no === value.re_mobile_no) {
this.inputType = 'text';
} else {
this.inputType = 'password';
}
});
<input NumbersOnly="true" [type]="inputType" placeholder="Enter Mobile no" formControlName="mobile_no" maxlength="10">
您可以创建一个keyup事件处理程序,如果b值在两种情况下都匹配,则将type
从密码更改为text
的HTML
<form novalidate>
<input type="text" (keyup)="checkEquality(ipField.value,passField.value)" #ipField>
<input [type]="ipType" (keyup)="checkEquality(ipField.value,passField.value)" #passField>
</form>
零件
export class AppComponent {
name = 'Angular';
ipType = ''
checkEquality(inField, passField) {
if (inField === passField) {
this.ipType = "text"
}
else {
this.ipType = "password"
}
}
}
这是演示
新属性:
formType ='密码'
然后将html输入类型更改为=
类型= {{formType}}
在构造函数中,现在是
constructor(private fb: FormBuilder){
this.cfForm = this.fb.group({
mobile_no: ['', [Validators.required, Validators.pattern('^[0-9]{10}$')]],
re_mobile_no: ['', [Validators.required, Validators.pattern('^[0-9]{10}$')]],
});
// Add the validator
this.cfForm.setValidators(this.checkIfEqual())
}
验证值是否匹配的新方法
public checkIfEqual() : ValidatorFn{
return (group: FormGroup): ValidationErrors => {
const control1 = group.controls['mobile_no'];
const control2 = group.controls['re_mobile_no'];
if(control1.value == control2.value){
this.formType = 'text';
} else{
this.formType = 'password'
}
return;
};
}
应该一切正常!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.