提问人:Perez Ch 提问时间:6/17/2021 更新时间:6/17/2021 访问量:2033
如何在 Typescript 中将蒙版应用于默认值
How to apply mask to a default value in Typescript
问:
我有一个 mask-phone 指令,当用户写入值时,它在输入中完美运行,但我需要设置默认值,并且我不知道如何在组件方法中应用 mask 指令。该值在没有掩码的情况下显示在输入中,只有当我修改该值时,掩码才会出现。
我遇到的问题是,在德国,电话号码有几种可能性,因此我无法在默认值中设置特定的掩码,例如: (49)(170)-1111111 (49)(1514)-1111111 (49)(25679)-1111111
我写了一个例子,你可以在下面的链接中看到:https://stackblitz.com/edit/angular5-phone-mask-directive-roeqfk?file=app/app.component.ts
提前致谢:)
答:
0赞
Tino
6/17/2021
#1
您可以从指令内部提供默认值,并在生命周期挂钩中设置掩码。这样做还有一个好处,即每次使用此指令时,默认值都是相同的。OnInit
法典:
import {Directive, ElementRef, HostListener, OnInit} from '@angular/core';
import {NgControl} from '@angular/forms';
@Directive({
selector: '[formControlName][appPhoneMask]'
})
export class PhoneMaskDirective implements OnInit{
defaultValue: string = '4912345678'
constructor(public ngControl: NgControl, private elementRef: ElementRef) { }
ngOnInit(): void {
this.applyMask(this.defaultValue)
}
@HostListener('ngModelChange', ['$event'])
onModelChange(event): void {
this.onInputChange(event, false);
}
@HostListener('keydown.backspace', ['$event'])
keydownBackspace(event): void {
this.onInputChange(event.target.value, true);
}
onInputChange(event, backspace): void {
let newVal = event.replace(/\D/g, '');
if (backspace && newVal.length <= 6) {
newVal = newVal.substring(0, newVal.length - 1);
}
this.applyMask(newVal)
}
applyMask (value): void {
if (value.length === 0) {
value = '';
} else if (value.length <= 3) {
value = value.replace(/^(\d{0,2})/, '($1)');
} else if (value.length <= 6) {
value = value.replace(/^(\d{0,2})(\d{0,3})/, '($1) ($2)');
} else if (value.length <= 12) {
value = value.replace(/^(\d{0,2})(\d{0,3})(\d{0,7})/, '($1) ($2)-$3');
} else if (value.length <= 13) {
value = value.replace(/^(\d{0,2})(\d{0,4})(\d{0,7})/, '($1) ($2)-$3');
} else if (value.length <= 14) {
value = value.replace(/^(\d{0,2})(\d{0,5})(\d{0,7})/, '($1) ($2)-$3');
} else {
value = value.substring(0, 14);
value = value.replace(/^(\d{0,2})(\d{0,5})(\d{0,7})/, '($1) ($2)-$3');
}
this.ngControl.valueAccessor.writeValue(value);
}
/** This method allows to keep the formControl value without the mask, in order to use it in backend queries */
@HostListener('input') onChange(): void {
const newVal = this.elementRef.nativeElement.value.replace(/\D/g, '');
this.ngControl.control.setValue(newVal, {
emitEvent: false,
emitModelToViewChange: false,
emitViewToModelChange: false
});
}
}
评论
0赞
Perez Ch
6/17/2021
在我的项目中,当我订阅后端时,我会收到一个电话列表,所以我需要从该响应中获取第一个电话,尽管一旦我将其设置为输入,它就会自动出现,但事实并非如此。我认为是的,指令 ngOnInit 是正确的地方,但是我如何将电话从组件发送到指令。
0赞
Perez Ch
6/18/2021
谢谢!我做到了,仍然不起作用,但这是因为指令以某种方式接收值为空,所以我会检查,因为在html中显示了该值,然后我不知道在哪里丢失了。
评论