[英]ngModel setting value after directive
我有以下問題:
我有一個像這樣的電話號碼輸入字段:
我想屏蔽55-5555-5555這樣的文本,所以我創建了一條指令:
import { Directive, HostListener } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[appPhoneNumber]'
})
export class PhoneNumberDirective {
constructor(public ngControl: NgControl) { }
ngOnInit() {
this.windowReady(this.ngControl.model);
}
windowReady(value) {
this.onInputChange(value, false);
}
@HostListener('ngModelChange', ['$event'])
onModelChange(event) {
this.onInputChange(event, false);
}
@HostListener('keydown.backspace', ['$event'])
keydownBackspace(event) {
this.onInputChange(event.target.value, true);
}
onInputChange(event, backspace) {
let newVal = event.replace(/\D/g, '');
if (backspace && newVal.length <= 6) {
newVal = newVal.substring(0, newVal.length - 1);
}
if (newVal.length === 0) {
newVal = '';
} else if (newVal.length <= 2) {
newVal = newVal.replace(/^(\d{0,3})/, '$1');
} else if (newVal.length <= 6) {
newVal = newVal.replace(/^(\d{0,2})(\d{0,4})/, '$1-$2');
} else if (newVal.length <= 10) {
newVal = newVal.replace(/^(\d{0,2})(\d{0,4})(\d{0,4})/, '$1-$2-$3');
} else {
newVal = newVal.substring(0, 10);
newVal = newVal.replace(/^(\d{0,2})(\d{0,4})(\d{0,4})/, '$1-$2-$3');
}
console.log("New value is: " + newVal);
this.ngControl.valueAccessor.writeValue(newVal);
}
}
這是輸入字段:
<mat-form-field style="width: 75%;">
<input matInput appPhoneNumber placeholder="Telefono" [(ngModel)]="person.numero_telefono">
</mat-form-field>
如您所見,輸入具有一個用於獲取和設置值的ngModel,我現在面臨的問題是當輸入首次出現且ngModel具有一個值時,該字段顯示的文本如下:
5555555555
代替:
55-5555-5555
我現在的理論是指令正在設置值:
this.ngControl.valueAccessor.writeValue(newVal);
在輸入本身之前:
<input matInput appPhoneNumber placeholder="Telefono" [(ngModel)]="person.numero_telefono">
因此,當輸入設置了值時,它將采用不帶掩碼的值,並覆蓋指令設置的文本。
有誰知道如何在ngModel之后調用該指令或對我有幫助的東西?
我相信您想要管道,而不是指令。 如果您看一下這篇文章,它將討論如何將管道與ngModel一起使用在Angular的INPUT元素上使用 ngModel中的管道
ng-mask可能就是您想要的。
<input matInput appPhoneNumber placeholder="Telefono" [(ngModel)]="person.numero_telefono" mask='55-5555-5555'>
這是更多信息的鏈接ng-mask
[(ngModel)]
或Input
控件沒有問題。 此問題的實際原因是matInput
指令。 只需刪除matInput
並檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.