首页 > 解决方案 > Angular 材质每 2 个字符后添加分号

问题描述

我有以下代码,它是用户可以输入 MAC 地址的 Angular Material 输入字段。我希望能够在用户输入的每 2 个字符后添加一个冒号(:)。而且如果用户删除冒号旁边的字符,它应该删除该特定冒号

<mat-form-field>
  <input matInput placeholder="MAC address" name="mac_address" required [(ngModel)]="model.mac_address" (blur)="validate()">
  <mat-error *ngFor="let error of errors_by_field['mac_address']">{{error.message}}</mat-error>
</mat-form-field>

任何想法如何在Angular 6中做到这一点?

标签: angularangular-material

解决方案


我会在您的输入中添加一个事件,然后使用model.mac_address.

<mat-form-field>
  <input matInput (keyup)="changedInput($event)" placeholder="MAC address" name="mac_address" required [(ngModel)]="model.mac_address" (blur)="validate()">
  <mat-error *ngFor="let error of errors_by_field['mac_address']">{{error.message}}</mat-error>
</mat-form-field>

然后添加函数

public changedInput(value){
 if(this.model.mac_address){
   //we do not need the value, we just update the formatedMac using this.model.mac_address
   const inputWithourColon = this.model.mac_address.replace(new RegExp(";", 'g'), "");
   let blocks = inputWithourColon.match(/.{1,2}/g);
   let formatedMac = blocks.shift();
   for (let block of blocks){
    formatedMac = formatedMac + ";" + block;
   }
   this.model.mac_address = formatedMac;
 }
}

编辑

我用 (keyup) 更改了 (change) 指令并更新了代码以在用户写入时在输入字段内写入格式化文本。


推荐阅读