繁体   English   中英

指令后的ngModel设置值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM