Добавьте этот компонент отображения/скрытия пароля в свое приложение Angular за 3 простых шага.

Шаг 1 — Создайте компонент Angular

  • Создайте компонент Angular с помощью ContentChild IonInput.
  • Добавьте метод переключения, который будет запускаться при нажатии на значок глаза.
  • Этот метод будет переключаться между отображением текста пароля и точек.
  • Определите логическую переменную showPassword.
import { Component, ContentChild } from '@angular/core';
import { IonInput } from '@ionic/angular';
@Component({
  selector: 'app-show-hide-password',
  templateUrl: './show-hide-password.component.html',
  styleUrls: ['./show-hide-password.component.scss']
})
export class ShowHidePasswordComponent {
  showPassword = false;
@ContentChild(IonInput) input: IonInput;
constructor() {}
toggleShow() {
    this.showPassword = !this.showPassword;
    this.input.type = this.showPassword ? 'text' : 'password';
  }
}

Шаг 2. Добавьте HTML-разметку для компонента.

  • Создайте простую привязку с помощью нашего метода переключения, привязанного к событию щелчка.
  • Измените значок с открытым или закрытым глазом в зависимости от переменной showPassword.
import { Component, ContentChild } from '@angular/core';
import { IonInput } from '@ionic/angular';
@Component({
  selector: 'app-show-hide-password',
  templateUrl: './show-hide-password.component.html',
  styleUrls: ['./show-hide-password.component.scss']
})
export class ShowHidePasswordComponent {
  showPassword = false;
@ContentChild(IonInput) input: IonInput;
constructor() {}
toggleShow() {
    this.showPassword = !this.showPassword;
    this.input.type = this.showPassword ? 'text' : 'password';
  }
}

Это мой show-hide-password.comComponent.scss, чтобы добавить несколько стилей.

:host {
  display: flex;
  width: 100%;
  align-items: center;
.type-toggle {
    padding-inline-start: 0.5rem;
.show-option,
    .hide-option {
      font-size: 1.2rem;
      display: block;
// In case you want to use text instead of icons
      &:not(ion-icon) {
        text-transform: uppercase;
        font-size: 1rem;
      }
    }
  }
}

Шаг 3 — Используйте компонент «Показать/Скрыть пароль»

Просто используйте компонент с ‹ion-input>< в качестве дочернего элемента контента.

<ion-item>
  <app-show-hide-password>
      <ion-input type="password" placeholder="Password" formControlName="password"></ion-input>
  </app-show-hide-password>
</ion-item>