【问题标题】:Angular 4 Change form input value to # while tyingAngular 4在绑定时将表单输入值更改为#
【发布时间】:2017-06-13 02:03:18
【问题描述】:

我试图模仿密码的作用,无论用户键入什么,它都被••••••• 代替,除了我想对数字执行此操作并且只显示最后四个数字。到目前为止,我的@Directive 中有捕获击键的事件,但实际上并没有在流中(在输入中)发出或传播任何更改来更改值。

例如。 #####1234

   <input id="indTaxId" type="text" name="indTaxId"
      [(ngModel)]="payLoadService.individual.taxId"
      required maxlength="9" pattern="^[0-9]{9}$"
      [lastFourDirective]="payLoadService.individual.taxId"
    (lastFourDirectiveOutput)="payLoadService.individual.taxId"
   />

last-four.directive.ts

@Directive({
  selector: '[lastFourDirective]'
})

export class LastFourDirective implements OnInit {

  private el: HTMLInputElement;

  constructor(
      private elementRef: ElementRef
  ) {
    this.el = this.elementRef.nativeElement;
  }

  ngOnInit() {
  }

  @Input() lastFourDirective: string;

  @HostListener('blur', ['$event.target.value'])
  onBlur(value) {
    console.log("blur", value);
   return this.lastFourDigits(value)
  }

  @HostListener('keyup', ['$event.target.value'])
  onKeyup(value) {
    console.log("keyup", value);
    return this.lastFourDigits(value)
  }

  private lastFourDigits(taxId: string) {
    return taxId.replace(/\d(?=\d{4})/g, '#')
  }
}

我怎样才能做到这一点?

PS:我没有使用 formControl,以上是我的输入示例。

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    您正在使用指令,因此您肯定需要在您的应用程序中执行此操作。我没有在 angular4 上工作过(我真的想,不知何故我可以在这里使用filter 但无法)但是如果全球不需要这种输入框,你为什么不写一个函数您的组件本身并在 (keyup) and (blur) 事件上触发它。例如:

    <input id="indTaxId" type="text" name="indTaxId"
           [(ngModel)]= payLoadService.individual.taxId
           required maxlength="9" pattern="^[0-9]{9}$"
           (keyup)="foo()"
           (blur)="foo()"
    />
    

    在你的组件中:

    foo() {
        this.payLoadService.individual.taxId = this.payLoadService.individual.taxId.replace(/\d(?=\d{4})/g, '#');
    }
    

    现在,如果您想通过指令实现,我没有答案,但如果您希望在多个地方使用此功能,我可以建议您另一种解决方案,您可以制作一个仅包含此功能的 password input component,即仅input box 并在任何你想要这样的输入框的地方使用这个组件。

    【讨论】:

    • 午夜时分,我也有同样的想法,并想我现在只在我的组件中执行此操作,并在需要时提取它。这做到了。谢谢@AshishRanjan
    猜你喜欢
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    相关资源
    最近更新 更多