show/hide password text using angular2

This is a better answer. Check below:

input

<input [type]="show ? 'text' : 'password'" />

click action

<button (click)="password()">{{show ? 'Show' : 'Hide'}}</button>

component

// variable - default false
show: boolean = false;

constructor() {
}

// click event function toggle
password() {
    this.show = !this.show;
}

in you html :

<div class="form-group">
    <label for="password">Password</label>
    <input type="password" class="form-control" #password-field>
    <span (click)="password-field.type=password-field.type=='password'?'text':'password'" 
    class="fa fa-fw field-icon toggle-password"
        [ngClass]="(password-field.type=='password')?' fa-eye':' fa-eye-slash'"></span>
</div>

in your css or sass

.field-icon {
  float: right;
  left: -15px;
  margin-top: -25px;
  position: relative;
  z-index: 2;
}

You need to use ViewChild() instead of ContentChild()

@ViewChild(ShowHideInput) input: ShowHideInput;

check your plunk

ContentChild() is for matching inside the transcluded content. e.g. contents inside <ng-content></ng-content>


You could also do all of this in the template in a quick and dirty way..

<input #x type="password">
<button (click)="x.type=x.type=='password'?'text':'password'"></button>

Tags:

Angular