Angular 掩码指令未屏蔽初始值
我正试图用Angular7实现一些输入掩码,使用这个问题的公认答案上的说明: 当我输入一个新值时,该代码工作正常。但是,当我用一个值初始化表单时,输入仍然是未屏蔽的。我已将原始问题的StackBlitz分叉以显示问题: 我的项目的相关代码如下: 赋值Angular 掩码指令未屏蔽初始值,angular,Angular,我正试图用Angular7实现一些输入掩码,使用这个问题的公认答案上的说明: 当我输入一个新值时,该代码工作正常。但是,当我用一个值初始化表单时,输入仍然是未屏蔽的。我已将原始问题的StackBlitz分叉以显示问题: 我的项目的相关代码如下: 赋值 updateForm():void{ this.renewalForm=this.fb.group({ customFields:this.fb.array(this.license.customFields.map(x=>this.fb.cont
updateForm():void{
this.renewalForm=this.fb.group({
customFields:this.fb.array(this.license.customFields.map(x=>this.fb.control(x.value)),
contacts:this.fb.array(this.license.contacts.map)(x=>this.fb.group({
触点类型:新的FormControl(x.type),
contactFirstName:new FormControl(x.firstName),
contactLastName:new FormControl(x.lastName),
contactPhone:new FormControl(x.phone),//您可以从onInputChange
提取格式化代码,将该代码放入formatValue
方法中,然后在ngOnInit
中调用该方法以格式化初始值:
ngOnInit() {
this.formatValue(this.ngControl.value, false);
}
onInputChange(event, backspace) {
this.formatValue(event, backspace);
}
formatValue(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 <= 3) {
newVal = newVal.replace(/^(\d{0,3})/, '($1)');
} else if (newVal.length <= 6) {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) ($2)');
} else if (newVal.length <= 10) {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '($1) ($2)-$3');
} else {
newVal = newVal.substring(0, 10);
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '($1) ($2)-$3');
}
this.ngControl.valueAccessor.writeValue(newVal);
}
ngOnInit(){
this.formatValue(this.ngControl.value,false);
}
onInputChange(事件,退格){
此.formatValue(事件、退格);
}
formatValue(事件、退格){
让newVal=event.replace(/\D/g');
if(backspace&&newVal.length)