[英]Angular 4 Change form input value to # while tying
我试图模仿用密码进行的操作,无论用户键入什么密码,都用•••••••
,除了我想对数字进行此操作,并且只显示最后四个数字。 到目前为止,我的@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({
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) 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
和在需要此类输入框的任何地方使用此组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.