【问题标题】:How to toggle the text with a button that hides and shows password value in Angular如何使用在 Angular 中隐藏和显示密码值的按钮切换文本
【发布时间】:2020-09-23 21:57:50
【问题描述】:

我正在使用 Angular 指令在表单中切换显示和隐藏密码字段。

我已经能够实现切换密码值的总体目标,但是,我似乎无法切换按钮中呈现的文本以反映输入字段的状态。

如何在用户单击按钮以显示输入的密码后将其文本切换为 HIDE,然后在用户单击按钮以隐藏密码后将其切换回 SHOW?

这里是代码库:

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');
    }
  }


}

HTML 模板:

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

查看结果演示:Password Toggle Demo

【问题讨论】:

    标签: javascript angular typescript angular2-directives angular2-hostbinding


    【解决方案1】:

    在onClick() 方法的末尾添加这段代码

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

    【讨论】:

      猜你喜欢
      • 2020-12-29
      • 1970-01-01
      • 2017-09-09
      • 2015-12-26
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多