gpt4 book ai didi

javascript - Angular 4 在绑定(bind)时将表单输入值更改为#

转载 作者:行者123 更新时间:2023-12-01 03:31:38 25 4
gpt4 key购买 nike

我试图模仿密码的操作方式,无论用户输入什么内容,它都会被 ••••••• 替换,除了我只想对数字执行此操作,并且仅对数字执行此操作显示最后四个数字。到目前为止,我的 @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"
/>

最后四.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,上面是我的输入示例。

最佳答案

您正在使用指令,因此您肯定需要在应用程序中执行此操作。我没有在 angular4 上工作过(我真的想,不知何故我可以在这里使用 filter 但无法),但如果没有这种输入框的全局需求,为什么不呢您在组件本身中编写一个函数,并在 (keyup) 和 (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, '#');
}

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

关于javascript - Angular 4 在绑定(bind)时将表单输入值更改为#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44511241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com