[英]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.