All files / password-strength si-password-strength.component.ts

100% Statements 17/17
100% Branches 0/0
100% Functions 4/4
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71                                                                    1x           16x   16x 16x         16x 16x 16x 16x 16x     1x       16x 16x 19x 19x 19x 19x 19x          
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import {
  AfterViewInit,
  Component,
  contentChild,
  contentChildren,
  ElementRef,
  input,
  signal
} from '@angular/core';
import { SiPasswordToggleComponent } from '@siemens/element-ng/password-toggle';
 
import { SiPasswordStrengthDirective } from './si-password-strength.directive';
 
@Component({
  selector: 'si-password-strength',
  imports: [SiPasswordToggleComponent],
  template: `
    <si-password-toggle [showVisibilityIcon]="showVisibilityIcon()" (typeChange)="toggle($event)">
      <ng-content />
    </si-password-toggle>
  `,
  styleUrl: './si-password-strength.component.scss',
  host: {
    '[class.bad]': 'bad()',
    '[class.weak]': 'weak()',
    '[class.medium]': 'medium()',
    '[class.good]': 'good()',
    '[class.strong]': 'strong()'
  }
})
export class SiPasswordStrengthComponent implements AfterViewInit {
  /**
   * Whether to show the visibility toggle icon.
   *
   * @defaultValue true
   */
  readonly showVisibilityIcon = input(true);
 
  private readonly passwordStrengthDirective = contentChildren(SiPasswordStrengthDirective);
  private readonly passwordInput = contentChild.required<
    SiPasswordStrengthDirective,
    ElementRef<HTMLInputElement>
  >(SiPasswordStrengthDirective, { read: ElementRef<HTMLInputElement> });
 
  protected readonly bad = signal(false);
  protected readonly weak = signal(false);
  protected readonly medium = signal(false);
  protected readonly good = signal(false);
  protected readonly strong = signal(false);
 
  protected toggle(type: string): void {
    this.passwordInput().nativeElement.type = type;
  }
 
  ngAfterViewInit(): void {
    this.passwordStrengthDirective().forEach(directive => {
      directive.passwordStrengthChanged.subscribe((strength: number | void) => {
        this.strong.set(strength === 0);
        this.good.set(strength === -1);
        this.medium.set(strength === -2);
        this.weak.set(strength === -3);
        this.bad.set(strength === -4);
      });
    });
  }
}