angular - 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中做到这一点?
解决方案
我会在您的输入中添加一个事件,然后使用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) 指令并更新了代码以在用户写入时在输入字段内写入格式化文本。
推荐阅读
- javascript - A-Frame:使用 set.Attribute 更改“可见”
- postgresql - 在 postgreSQL 中插入嵌套的 json 文件
- google-play-console - 无法在 Google Play 控制台中发布应用的初始版本
- angular - 如何更改owlDateTime 中的默认时间值?
- javascript - 如何用 Sinon JS 测试异步功能?
- html - 如何更改悬停选择选项的背景颜色?
- html - 面包屑项目的边框着色
- batch-file - Windows 批处理循环变量以
- asp.net-web-api - 空请求正文拒绝请求
- html - 如何为多个背景图像设置动画?