Angular2 - cannot change input type dynamically

14,182

Solution 1

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

Solution 2

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';
  }
Share:
14,182
ymrs
Author by

ymrs

Updated on June 05, 2022

Comments

  • ymrs
    ymrs almost 2 years

    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?

  • Ramesh Rajendran
    Ramesh Rajendran about 6 years
    I hope he want to change the type at default load.
  • ymrs
    ymrs about 6 years
    <user-input [type]="isActive ? 'password' : 'text'"></user-input> doesn't work either.
  • ymrs
    ymrs about 6 years
    @Anas Bin Nazeer, unfortunately i don't have a button on the page to do this. I want to be able to change the type on load.