如何通过 Angular 中的自定义掩码强制绑定 属性 5

How to force binding property through custom mask in Angular 5

我正在处理将一些输入屏蔽为货币格式的问题。我找到了一个不错的插件,目前可以正常工作。

每次使用键盘在 <input> 中输入内容时,掩码都可以正常工作。

但我在 input 标签下选择了 buttons,它提供了一些默认 "hint" 值供用户单击。

单击其中一个按钮时,我调用 click() 回调以绑定后面的 属性,这是有效的,但未应用遮罩。

如何更新输入以将掩码应用到绑定 属性??

我正在使用 Ionic 框架 3,angular 5

我的html:

<form [formGroup]="ammountForm">
    <ion-item class="input-item">
      <ion-input type="tel" [textMask]="{mask: ammountMask, guide: false}" placeholder="Ingresa el valor" formControlName="ammount"
        [(ngModel)]="ammount"></ion-input>
    </ion-item>

    <ion-item class="err-hint" no-lines *ngIf="ammountForm.controls.ammount.invalid">
      <p>La cantidad ingresada no es correcta</p>
    </ion-item>

    <ion-slides>
      <ion-slide class="def-slide" *ngFor="let ammount of defaultAmmounts">
        <button (click)="onSlideClick(ammount)" class="slide-btn" ion-button color="light-blue-grey" outline>${{ammount}}</button>
      </ion-slide>
    </ion-slides>
    <button class="continue-btn" color="cornflowerblue" [disabled]="ammountForm.controls.ammount.invalid" ion-button [full]="isMobile ? '' : null"
      (click)="triggerPhase4(phoneNumber)">Continuar</button>
  </form>

这是我将掩码 (ammountMask) 传递给输入的地方:

<ion-input type="tel" [textMask]="{mask: ammountMask, guide: false}" placeholder="Ingresa el valor" formControlName="ammount"
    [(ngModel)]="ammount"></ion-input>

以及在我的 ts 文件中发生绑定的回调:

onSlideClick(ammount: number) {
   this.ammount = ammount;
}

这里有一些图片可以给你一个想法。

任何关于如何解决这个问题的想法将不胜感激

编辑:这是我声明要使用的掩码的地方

import createNumberMask from 'text-mask-addons/dist/createNumberMask'

ngOnInit() {
this.phoneMask = BdbMaskProvider.phoneMask;
this.ammountMask = createNumberMask({})
}

他们有一个以编程方式设置值的错误(来源:https://github.com/text-mask/text-mask/issues/696

修复它的一种方法(在上面的 link 中建议)是通过引用输入并调用它们用于屏蔽的方法:

@ViewChild('telInputRef')
inputElement: MaskedInputDirective; 

onSlideClick(ammount: number) {
   this.inputElement.onInput(ammount);
}

您还需要将选择器引用添加到您的输入元素,然后才能像 <ion-input #telInputRef></ion-input>

感谢@DainiusLuksa 指出问题,

我在同一个线程上得到了另一个解决方法的建议

https://github.com/text-mask/text-mask/issues/696

我必须修改语法才能访问离子组件的本机元素:

@ViewChild('ammountRef', { read: ElementRef}) inputElement: any;

onSlideClick(ammt: number) {
//set value to form control in order get the validators
this.ammountForm.controls['ammount'].setValue(ammt);

//fire event to force new input through mask
if (this.inputElement != undefined) {
  const input = this.inputElement.nativeElement;
  input.value = ammt;
  input.dispatchEvent(new Event('input'));

}
}

并在 Html 中添加选择器:

<ion-input id="ammtRef" type="tel" [textMask]="{mask: ammountMask, guide: false}" placeholder="Ingresa el valor" formControlName="ammount"
        #ammountRef></ion-input>

如果您正在使用 FormGroup,请确保您也以编程方式设置值,因为仅通过设置输入元素验证器将无法工作