I was wondering if anyone can help explain why i am unable to change form input type dynamically?
For e.g.
<user-input type="{{ isActive ? 'password' : 'text' }}"></user-input>
doesn't work.
But this works,
<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();
}
}
}
The issue i have is that when i set the type dynamically, the user-input-password directive doesn't get triggered. If i set the type to password directly then it does get trigged.
Is there another way to dynamically change input type?
try this
<user-input [type]="isActive ? 'password' : 'text'"></user-input>
Please take a look at this
Dynamically generate input field type with angular 2 and set the type of the field
You can prefer this way. works most time:
<user-input #input type="password" ></user-input>
<button (click)="changeInput(input)">Change input</button>
ts file
changeInput(input: any): any {
input.type = input.type === 'password' ? 'text' : 'password';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With