[英]Angular 4 Change form input value to # while tying
I am trying to mimic what is done with passwords, where whatever an user types, it is substituted by •••••••
, except that I want to do this for numbers and only show the last four numbers. 我试图模仿用密码进行的操作,无论用户键入什么密码,都用
•••••••
,除了我想对数字进行此操作,并且只显示最后四个数字。 So far I have the events in my @Directive
that capture the keystrokes, but don't actually emit or propagate any change up the stream (in the input) to change the value. 到目前为止,我的
@Directive
中具有捕获击键的事件,但实际上并没有在流中(在输入中)发出或传播任何更改来更改值。
Ex. 例如
#####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, '#')
}
}
How can I accomplish this? 我该怎么做?
PS: I'm not using formControl, above is a sample of my input. PS:我没有使用formControl,上面是我输入的示例。
You are using a directive so certainly there is a global need for you to do this in your application. 您正在使用指令,因此肯定会在全球范围内需要您在应用程序中执行此指令。 I haven't worked on angular4 (I really thought, somehow I could use a
filter
here but was unable) but if there isn't a global need for this kind of input box, why don't you write a function in your component itself and trigger it on (keyup) and (blur)
events. 我还没有研究angular4(我真的认为,我可以在这里使用
filter
,但是无法使用),但是如果对于这种输入框没有全局需求,那么为什么不在组件中编写函数呢?本身,并在(keyup) and (blur)
事件上触发它。 For example: 例如:
<input id="indTaxId" type="text" name="indTaxId"
[(ngModel)]= payLoadService.individual.taxId
required maxlength="9" pattern="^[0-9]{9}$"
(keyup)="foo()"
(blur)="foo()"
/>
and in your component: 并在您的组件中:
foo() {
this.payLoadService.individual.taxId = this.payLoadService.individual.taxId.replace(/\d(?=\d{4})/g, '#');
}
Now I don't have an answer if you want to implement through a directive, but I can suggest you another solution if you want this functionality at multiple places, you can make a password input component
containing only this functionality ie only the input box
and use this component wherever you want such input boxes. 现在,如果您要通过指令来实现,我没有答案,但是如果您想在多个地方使用此功能,我可以建议您另一个解决方案,可以制作一个仅包含此功能的
password input component
,即仅input box
和在需要此类输入框的任何地方使用此组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.