Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - cannot change input type dynamically

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?

like image 432
ymrs Avatar asked Apr 03 '18 05:04

ymrs


2 Answers

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

like image 180
Ramesh Rajendran Avatar answered Oct 26 '22 01:10

Ramesh Rajendran


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';
  }
like image 30
Anas Avatar answered Oct 26 '22 01:10

Anas