From 02bed9d1245c032306c1466351140d4736f61baf Mon Sep 17 00:00:00 2001 From: Spencer Ofwiti Date: Mon, 28 Dec 2020 12:04:47 +0300 Subject: [PATCH] Add password toggle directive. --- src/app/_directives/index.ts | 1 + .../password-toggle.directive.spec.ts | 8 +++++ .../_directives/password-toggle.directive.ts | 36 +++++++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 src/app/_directives/index.ts create mode 100644 src/app/_directives/password-toggle.directive.spec.ts create mode 100644 src/app/_directives/password-toggle.directive.ts diff --git a/src/app/_directives/index.ts b/src/app/_directives/index.ts new file mode 100644 index 0000000..acdd4fe --- /dev/null +++ b/src/app/_directives/index.ts @@ -0,0 +1 @@ +// export * from 'password-toggle.directive'; diff --git a/src/app/_directives/password-toggle.directive.spec.ts b/src/app/_directives/password-toggle.directive.spec.ts new file mode 100644 index 0000000..dab2c6e --- /dev/null +++ b/src/app/_directives/password-toggle.directive.spec.ts @@ -0,0 +1,8 @@ +import { PasswordToggleDirective } from './password-toggle.directive'; + +describe('PasswordToggleDirective', () => { + it('should create an instance', () => { + const directive = new PasswordToggleDirective(); + expect(directive).toBeTruthy(); + }); +}); diff --git a/src/app/_directives/password-toggle.directive.ts b/src/app/_directives/password-toggle.directive.ts new file mode 100644 index 0000000..37e2f6f --- /dev/null +++ b/src/app/_directives/password-toggle.directive.ts @@ -0,0 +1,36 @@ +import {Directive, ElementRef, Input, Renderer2} from '@angular/core'; + +@Directive({ + selector: '[appPasswordToggle]' +}) +export class PasswordToggleDirective { + @Input() + id: string; + iconId: string; + + constructor( + private elementRef: ElementRef, + private renderer: Renderer2, + ) { + this.renderer.listen(this.elementRef.nativeElement, 'click', () => { + this.togglePasswordVisibility(); + }); + } + + togglePasswordVisibility(): void { + const password = document.getElementById(this.id); + const icon = document.getElementById(this.iconId); + // @ts-ignore + if (password.type === 'password') { + // @ts-ignore + password.type = 'text'; + icon.classList.remove('fa-eye'); + icon.classList.add('fa-eye-slash'); + } else { + // @ts-ignore + password.type = 'password'; + icon.classList.remove('fa-eye-slash'); + icon.classList.add('fa-eye'); + } + } +}