如何将输入字段类型= "password"转换为类型= "text"角度?



你能告诉我如何在角度中将输入字段类型="密码"转换为类型="文本"吗?在我的演示中,我有两个输入字段Mobile noRe-enter mobile number我希望如果用户输入两个相同的10数字,那么它将类型="密码"转换为类型="文本">

示例:如果您输入手机号码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,并且输入类型将更改。

见斯塔克闪电战

这应该适合您:侦听表单值的变化,如果值匹配,则更改输入的类型

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 事件处理程序,如果 bthe 值在两种情况下都匹配,则将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"
}
}
}

这是演示

你可以试试[type]

我已经在堆栈闪电战上创建了演示

<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">

新属性:

表单类型 = '密码'

然后将 html 输入类型更改为 =

类型= {{表单类型}}

在构造函数中,现在是

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;
};

}

应该都行!

最新更新