0
如何在不改變實際值的情況下屏蔽除Angular 4中的最後四個輸入以外的輸入中的所有字符(即show *)?輸入中的Angular4遮罩字符不改變其值
例如:號碼應該像這樣*** 1234的輸入文本框內部和值應爲7671234.
如何在不改變實際值的情況下屏蔽除Angular 4中的最後四個輸入以外的輸入中的所有字符(即show *)?輸入中的Angular4遮罩字符不改變其值
例如:號碼應該像這樣*** 1234的輸入文本框內部和值應爲7671234.
如果你想使用該指令在TemplateDriveForm使用指令
@Directive({
selector: '[stringHide]'
})
export class StringDirective implements OnInit {
private value: any; //the variable where we save the "true value"
private element: HTMLInputElement
constructor(private el: ElementRef, private form: ControlContainer) {
this.element = el.nativeElement;
}
ngOnInit() { //It's necesary use OnInit, otherwise the first time not formtted
this.value = this.element.value;
this.formatValue();
}
@HostListener('input') onChange() { //when a change happens save the value in a variable
this.value = this.element.value;
}
@HostListener('blur') onBlur() { //when lost the focus call format function
this.formatValue();
}
@HostListener('focus') onFocus() { //when get the focus recover the true value
this.element.value = this.value;
}
formatValue() { //here, change the apperance of the input
//I choose that if the value.length>14 only show 10 "*"
let len=this.element.value.length;
this.element.value = (len <= 4) ? this.element.value:
(len>14)? "**********"+this.element.value.substr(len - 4):
"**************".substring(0,len-4)+this.element.value.substr(len - 4);
}
}
你必須添加AfterViewChecked事件,因爲在ngOnInit我們不能得到的「真正價值」
@Directive({
selector: '[stringHide]'
})
export class StringDirective implements OnInit,AfterViewChecked { //<--AddAfterViewChecked
private value: any;
private initialized:boolean; //<--add a new variable
....
//Add ngAfterViewCheckecd
ngAfterViewChecked()
{
if (this.element.value && !this.initialized)
{
this.initialized=true;
this.value = this.element.value;
this.formatValue();
}
}
.....
將這項工作如果移動在輸入框中光標? – georgeawg
該指令在Reactive Form中正常工作。當這個指令與模板驅動的表單一起使用時會有問題。如果我能解決,我會改變代碼 – Eliseo