javascriptangulartypescriptangular2-directivesangular2-hostbinding

How to toggle the text with a button that hides and shows password value in Angular


I am using an Angular Directive to toggle showing and hiding password fields in a form.

I have been able to achieve the overall objective of toggling the password's value however, I cannot seem to be able to toggle the text that is rendered in the button to reflect the state of the input field.

How can I be able to toggle the button's text to HIDE once a user clicks on it to reveal the entered password, then toggle it back to SHOW once the user clicks the button to hide the password?

Here is the code base:

import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';

@Directive({
  selector: '[passToggle]'
})
export class ToggleDirective {
  visible: boolean = false;

  constructor(private el: ElementRef, private renderer: Renderer2) { }

  div = this.renderer.createElement('div');
  span = this.renderer.createElement('span');

  ngOnInit() {
    this.buildInputAppend();
  }

  buildInputAppend () {
    this.renderer.addClass(this.div, 'input-group-append');
    this.renderer.addClass(this.span, 'input-group-text');

    const text = this.renderer.createText('Show');

    this.renderer.appendChild(this.span, text);
    this.renderer.appendChild(this.div, this.span);

    this.renderer.appendChild(this.el.nativeElement, this.div);
  }

  @HostListener('click') onClick() {
    this.visible = !this.visible;

    const parent = this.el.nativeElement.parentNode;
    const input = this.el.nativeElement.firstChild;

    if (!this.visible) {
      input.setAttribute('type', 'text');
    } else {
      input.setAttribute('type', 'password');
    }
  }


}

The HTML template:

<div class="form-group">
  <div class="input-group" passToggle>
    <input class="form-control" type="password"formControlName="password" >
  </div>
</div>

To view a demo of the result: Password Toggle Demo


Solution

  • Add this piece of code at the end of your onClick() method

    this.span.innerText = this.toggleName('Show', 'Hide');