2017-06-13 29 views
0

我試圖模仿用密碼完成的操作,無論用戶輸入什麼內容,它都會被•••••••代替,除了我想對數字執行此操作並僅顯示最後一個四個數字。到目前爲止,我的@Directive中的事件捕獲鍵擊,但實際上並未發射或傳播流(輸入中)的任何更改以更改值。Angular 4將表單輸入值更改爲#綁定時

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" 
    /> 

最後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,上面是我的輸入樣本。

回答

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,並在需要此類輸入框的任何地方使用此組件。

+0

周圍午夜我有同樣的想法,並認爲我現在只是在我的組件中做並在需要時提取它。這做到了。謝謝@AshishRanjan – Diego

+0

歡迎:) –