[英]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.