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